Java Collections Framework
1. 主要接口
2. 主要实现
JDK | Interface | Implementation | |||||||
Heap | Hash Table | Resizable Array | Balanced Tree | Linked List | Hash Table + Linked List | Legacy
| Special | ||
1.4 | Set |
| HashSet |
|
|
| LinkedHashSet | Vector |
|
1.4 | SortedSet |
|
|
| TreeSet |
|
|
|
|
1.4 | List |
|
| ArrayList |
| LinkedList |
|
|
|
1.4 | Map |
| HashMap |
|
|
| LinkedHashMap | Hashtable | WeakHashMap IdentityHashMap |
1.4 | SortedMap |
|
|
| TreeMap |
|
|
|
|
1.5 | ConcurrentMap |
| ConcurrentHashMap |
|
|
|
|
|
|
1.5 | Queue | AbstractQueue PriorityQueue |
|
|
| ConcurrentLinkedQueue |
|
|
|
1.5 | BlockingQueue | PriorityBlockingQueue DelayQueue SynchronousQueue |
| ArrayBlockingQueue |
| LinkedBlockingQueue |
|
|
|
3. 主要属性
| 接口还是实现 | 是否同步 | 是否包含重复数据 | 是否允许Null | 是否有序 | 备注 |
Collection | Interface |
|
|
|
| 一组数集合 |
Set | I |
| 否 |
|
| 相当于数学上的集合,不能有重复数据 |
| Imp | 否 | 否 |
| 否 |
|
| Imp | 否 | 否 |
|
|
|
| Imp | 否 | 否 |
|
| Hash表+linked list,按照插入set的顺序排列,可以保证顺序,效率仅次于HashSet |
SortedSet | I |
| 否 |
| 是 | 自然升序的Set |
List | I |
| 是 |
| 是 | 一个有序的集合 |
| Imp | 否 | 是 | 是 | 是 | 一般来讲效率最好,对于随意访问,效率好
允许null值,大体等于Vector,只是unsynchronized |
| Imp | 否 | 是 | 是 | 是 | 对于随意插入效率好 unsynchronized |
Vector | Imp | 是 | 是 | 否 | 是 | Synchronized |
Queue | I |
| 是 |
| 是 | 有序,可以包含重复数据,一般FIFO |
Map | I |
|
|
|
| key-value对集合,不能有重复数据,1个key最多一个值 |
HashMap | Imp | 否 | 是 | 是 | 否 | 与Hashtable大致相同,除了unsynchronized和允许Null |
LinkedHashMap | Imp | 否 | 是 | 是 | 是 |
|
Hashtable | Imp | 是 | 是 | 否 | 否 | Synchronized,不允许Null |
SortedMap | I |
|
|
|
| 自然升序的Map |
4. Iterator
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
a) 最方便的删除
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
b) fail-fast
The iterators returned by the this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
c) ListIterator的n+1个index
5. 同步处理
除Vector和Hashtable外,其余均为unsynchronized。以ArrayList为例子,如果在多thread情况下使用ArrayList,如果有其他线程修改了ArrayList的结构(修改值可以),必须自己进行手工同步操作。
List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
相应的其他方法:
static Collection | synchronizedCollection(Collection c) |
static List | synchronizedList(List list) |
static Map | synchronizedMap(Map m) |
static Set | synchronizedSet(Set s) |
static SortedMap | synchronizedSortedMap(SortedMap m) |
static SortedSet | synchronizedSortedSet(SortedSet s) |