Java Collection Framework

Outline

https://docs.oracle.com/javase/7/docs/technotes/guides/collections/reference.html

Collections

4大数据类型

Collection
  List
    ArrayList
    LinkedList
    Vector
  Set
    HashSet
    TreeSet
    LinkedHashSet
  Queue
    LinkedList
    PriorityQueue

Map
  HashMap
  Hashtable
  LinkedHashMap
  TreeMap

Access Collection Class

Add / Remove

boolean didCollectionChange = collection.add(anElement);
boolean wasElementRemoved   = collection.remove(anElement); 

Check

boolean containsElement = collection.contains("an element");
boolean containsAll     = collection.containsAll(elements);

Iteration

// method 1
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
    Object object = iterator.next();
    //do something to object;    
}

// method 2
for(Object object : collection) {
  //do something to object;
}

Access Map Class

Add

Map mapA = new HashMap();
mapA.put("key1", "element 1");

Remove

remove(Object key)

Get

String element1 = (String) mapA.get("key1");

Iteration

// key iterator
Iterator iterator = mapA.keySet().iterator();

// value iterator
Iterator iterator = mapA.values();

Differences

ArrayList v.s. LinkedList

ArrayList v.s. Vector

HashMap v.s. Hashtable

(To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. parameter: initialCapacity, loadFactor)

HashMap v.s. ConcurrentHashMap

Hashtable v.s. ConcurrentHashMap

参考 -> http://blog.csdn.net/wisgood/article/details/19338693

Fail-fast and Fail-safe Collection

fail-safefail-fast是修饰Collection的概念。它们关心的问题是:当在 iterate 一个 collection 时,这个 collection 本身发生了变化怎么办?

fail-fast

ArrayList<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add(3);
Iterator<Integer> itr = integers.iterator();

while (itr.hasNext()) {
    Integer a = itr.next();
    integers.remove(a);
}

原理:集合内部有一个flag modCount,每当集合发生了变化,就+1。如果在循环中,发现 modCount 和初始值不一样时,就抛出异常。

需要特别注意的是:如果我们修改的是iterator,而不是collection,是不会报错的!因为iterator内部调用了collection的API去修改值,且会重置modCount的初始值。见下例:

Iterator<Integer> itr = integers.iterator();
while (itr.hasNext()) {
    if (itr.next() == 2) {
        // will not throw Exception
        itr.remove();
    }
}

fail-safe

List<Integer> integers = new CopyOnWriteArrayList<>();
integers.add(1);
integers.add(2);
integers.add(3);
Iterator<Integer> itr = integers.iterator();

while (itr.hasNext()) {
    Integer a = itr.next();
    integers.remove(a);
}

CopyOnWriteArrayList,顾名思义,是ArrayList的一个线程安全的变体,其中所有可变操作add, set 等等,都是通过对底层数组进行一次新的复制来实现的。

参考以下文章:

Fork me on GitHub