list集合
**繼承了Collection接口
特點:有序,可重複
常見實現類 ArrayList Vector LinkedList Stack
ArrayList
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable //實現了Serializable接口,所以它支持序列化,可以通過序列化傳輸 //實現了RandomAccess接口,支持快速隨機訪問,就是通過下標序號進行快速訪問 //實現了Cloneable接口,支持被克隆
//transient關鍵字修飾的變量無法被序列化,前提是該類必須實現接口Serializable private transient Object[] elementData; //底層由數組實現 private int size;//集合中包含的元素的數量,增加或者刪除集合元素時修改這個值
構造方法
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); //構造一個指定大小的數組 this.elementData = new Object[initialCapacity]; } //重載一個無參構造方法 public ArrayList() { this(10); //調用有參構造並設置默認容量爲10 }
ArrayList的add方法
public boolean add(E e) { ensureCapacityInternal(size + 1);//數組大小+1 elementData[size++] = e;//將新下標和參數對應 return true; } //重載的add方法 public void add(int index, E element) { rangeCheckForAdd(index); //檢查參數index是否越界 ensureCapacityInternal(size + 1); //拷貝了一個新數組賦值給自己 System.arraycopy(elementData,index,elementData,index + 1, size - index); elementData[index] = element; size++;//集合大小自增 } 拷貝方法 static void arraycopy(Object source, //原數組 int beginIndex,// 從原數組開始複製的下標 Object destination,// 新數組 int destStartIndex, // 新數組開始粘貼的下標 int length) //複製長度
addAll方法
//將Collection c內的數據插入ArrayList中 public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray();//轉換成對象數組 int numNew = a.length;//記錄對象數組長度 ensureCapacityInternal(size + numNew); System.arraycopy(a, 0, elementData, size, numNew);//拷貝數組 size += numNew;//拓展集合的大小 return numNew != 0;//根據對象數組的大小是否爲零判斷 } //將Collection c中的數據插入到ArrayList的指定位置 public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index);//檢查添加元素的邊界 Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew);//拓展集合容量 int numMoved = size - index;//記錄插入位置 if (numMoved > 0) //先拷貝index + numNew以後的內容給自己 System.arraycopy(elementData, index, elementData, index + numNew, numMoved); //再將index之前的內容拷貝進來 System.arraycopy(a, 0, elementData, index, numNew); size += numNew;//拓展集合大小 return numNew != 0; }