Java基礎,java基礎知識總結
集合包括常用的ArrayList、HashMap、HashSet,也有不常用的Stack、Queue,有安全執行緒的Vector、HashTable,也有線程不安全的LinkedList、TreeMap等。
ArrayList是實現List介面的動態數組,初始容量10,即數組大小。在每次向容器中增加元素的同時都會進行容量檢查,當快溢出時,就會進行擴容操作(資料向新數組的重新拷貝)。不是同步的,多線程中使用,最好在建立的時候保證同步。
例如 :
List list = Collections.synchronizedList(new ArrayList());
建立:即建立一個transient修飾的數組。
新增:
方法:add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)、set(int index, E element)
通常會先一步檢測容器大小,查看是否需要擴容。調用ensureCapacity()方法對ArrayList集合進行擴容操作
public void ensureCapacity(int minCapacity) { //修改計時器 modCount++; //ArrayList容量大小 int oldCapacity = elementData.length; /* * 若當前需要的長度大於當前數組的長度時,進行擴容操作 */ if (minCapacity > oldCapacity) { Object oldData[] = elementData; //計算新的容量大小,為當前容量的1.5倍 int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; //數組拷貝,產生新的數組 elementData = Arrays.copyOf(elementData, newCapacity); } }
若為指定index位置插入元素add(int index, E element),會調用System.arraycopy()方法,目的就是將index位置空出來以供新資料插入,這裡需要進行數組資料的右移,這是非常麻煩和耗時的,所以如果指定的資料集合需要進行大量插入操作,推薦使用LinkedList。
刪除:
方法:remove(int index)、remove(Object o)、removeRange(int fromIndex, int toIndex)、removeAll()
刪除元素後,會調用System.arraycopy(...)方法對剩餘元素位置進行調整
擷取:
方法:get(int index)
由於ArrayList是動態數組,所以我們完全可以根據下標來擷取ArrayList中的元素,而且速度還比較快,故ArrayList適於隨機訪問
LinkedList是實現List介面的鏈表,插入和刪除時優於ArrayList,而隨機訪問則比ArrayList遜色些。