/** * 顺序表,重点是数组动态扩容,插入 * 底层采用数组,长度可以动态变化,此处采用增长一倍,而java.util.ArrayList每次增长50% * int newCapacity = oldCapacity + (oldCapacity >> 1); * */ public class ArrayList implements List{ private Object[] elementData;//底层数组 private int size;//元素个数 public ArrayList(int initialCapacity) { //给数组分配指定数量空间 elementData = new Object[initialCapacity]; //指定顺序表元素个数,默认是0 //size = 0; } public ArrayList() { //没有指定长度,默认initialCapacity是4 this(4); //没有指定长度,长度是0 // elementData = new Object[]{}; } @Override public int size() { // TODO Auto-generated method stub return size; } @Override public Object get(int i) { if(i<0||i>size-1){ throw new RuntimeException("数组指针越界:"+i); } return elementData[i]; } @Override public boolean isEmpty() { // TODO Auto-generated method stub return size == 0; } @Override public boolean contains(Object e) { // TODO Auto-generated method stub return false; } @Override public int indexOf(Object e) { // TODO Auto-generated method stub return 0; } @Override public void add(int i, Object e) { if(i<0||i>size){ throw new RuntimeException("数组指针越界异常:"+i); } if(size == elementData.length) { grow(); } for(int j =size ; j>i ; j--){ elementData[j] = elementData[j-1]; } elementData[i] = e; size++; } @Override public void add(Object e) { this.add(size, e); // //动态扩容 // if(size == elementData.length) // { // grow(); // } // elementData[size] = e; // size++; // //System.out.println("length="+elementData.length); } public void grow(){ // Object[] newArr = new Object[size*2]; // for(int i = 0; i<size;i++){ // newArr[i] = elementData[i]; // } // elementData = newArr; elementData = Arrays.copyOf(elementData, elementData.length*2); } }