集合1
集合
創建集合時不跟泛型
編譯器檢查不出元素的類型,取元素時需要強轉,若強轉類型不對則報異常
使用Arrays.asList()生成的List
進行add()或delet()操作運行時會出異常,因為Arrays.asList()的底層為數組,長度不可改變
分類
Collection
List
ArrayList LinkedList
- set
queue
map
List
ArrayList
add(int index, E element) 將指定的元素插入此列表中的指定位置。
默認使用System.arraycopy方法進行挪移元素
線程不安全:
List list = Collections.synchronizedList(new ArrayList(...));//進行同步容量大小和元素個數的關系??
default關鍵字(虛擬擴展方法),List接口實現了sort()方法,可以在接口裏對方法實現
叠代器
Iterator
- boolean hasNext() 如果仍有元素可以叠代,則返回 true
- E next() 返回叠代的下一個元素
- void remove() 從叠代器指向的 collection 中移除叠代器返回的最後一個元素(可選操作)
- default void forEachRemaining(Consumer<? super E> action)
ArrayList叠代器如下
private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
不允許在foreach裏刪除或添加操作(來自<<阿裏巴巴Java開發手冊>>)
List<String> a = new ArrayList<>(); a.add("1"); a.add("2"); for (String string : a) { if("2".equals(string)) { a.remove(string); } System.out.printlb(String); }
異常: java.util.ConcurrentModificationException
分析:
remove("1")
第一輪: cussor=0,size=2,取出"1"後cussor+1,刪除"1"後size=1
第二輪: cussor=1,size=1, 經hasNext()判斷結束循環,元素"2"沒有得到遍歷
remove("2")
第一輪: cussor=0,size=2,取出"1"後cussor+1,size不變
第二輪: cussor=1,size=2, 取出"2"後cussor+1,刪除"2"後size=1
第三輪: cussor=2,size=1,hasNext()為true不能結束循環,此時進入next()方法內的checkForComodification()方法就拋出異常
集合1