Collection 和 Collections
首先要明確的是,Collection 和 Collections是兩個(gè)不同的概念。Collection是一個(gè)接口,所有的集合類(除Map外)都要繼承(實(shí)現(xiàn))自該接口。它提供了對(duì)集合對(duì)象進(jìn)行基本操作的通用接口方法。Collections是一個(gè)包裝類,它包含有各種有關(guān)集合操作的靜態(tài)多態(tài)方法。(Collections是一個(gè)工具類,不能實(shí)例化)
Collection家族關(guān)系圖
一、Vector、LinkedList、ArrayList
區(qū)別 http://www.hollischuang.com/archives/1349
-
Vector、ArrayList是使用數(shù)組實(shí)現(xiàn)的,LinkedList是使用鏈表實(shí)現(xiàn)的
2)Vector是線程安全的,LinkedList、ArrayList不是線程安全的
如果涉及到多線程,那么就選擇
Vector,如果不涉及到多線程就從LinkedList、ArrayList中選。LinkedList更適合從中間插入或者刪除(鏈表的特性)。ArrayList更適合檢索和在末尾插入或刪除(數(shù)組的特性)。
PS: Collections.synchronizedList(List list)方法也可以用來(lái)返回一個(gè)線程安全的List。參見(jiàn)SynchronizedList和Vector的區(qū)別
Map家族的關(guān)系圖
二、HashMap、HashTable、ConcurentHashMap
HashMap和HashTable都實(shí)現(xiàn)了Map接口,ConcurrentHashMap實(shí)現(xiàn)了ConcurrentMap接口HashMap和ConcurrentHashMap都繼承了AbstractMap類,HashTable繼承了Dictionary類
3)HashTable和ConcurrentHashMap是線程安全的,HashMap不是線程安全的。
當(dāng)一個(gè)線程訪問(wèn)
HashTable的同步方法時(shí),其他線程訪問(wèn)HashTable的同步方法時(shí),可能會(huì)進(jìn)入阻塞或輪詢狀態(tài)。ConcurrentHashMap使用鎖分段技術(shù),將數(shù)據(jù)分成一段一段的存儲(chǔ),給每一段數(shù)據(jù)配一把鎖,當(dāng)一個(gè)線程占用鎖訪問(wèn)其中一個(gè)段數(shù)據(jù)的時(shí)候,其他段的數(shù)據(jù)也能被其他線程訪問(wèn)。
如果不涉及到多線程處理的情況,就是用hashMap,因?yàn)樗男时容^高。在有并發(fā)請(qǐng)求的場(chǎng)景中,如果數(shù)據(jù)的強(qiáng)一致性比較重要,那么就請(qǐng)使用hashTable,因?yàn)镃oncurrentHashMap的get,clear,iterator 都是弱一致性的。如果效率要求比較高,那么就使用ConcurrentHashMap,因?yàn)樗粫?huì)像hashTable那樣產(chǎn)生阻塞。
關(guān)系圖譜
代碼示例
下面是一個(gè)簡(jiǎn)單的例子來(lái)說(shuō)明一些集合類型:
List<String> a1 = new ArrayList<String>();
a1.add("Program");
a1.add("Creek");
a1.add("Java");
a1.add("Java");
System.out.println("ArrayList Elements");
System.out.print("\t" + a1 + "\n");
List<String> l1 = new LinkedList<String>();
l1.add("Program");
l1.add("Creek");
l1.add("Java");
l1.add("Java");
System.out.println("LinkedList Elements");
System.out.print("\t" + l1 + "\n");
Set<String> s1 = new HashSet<String>(); // or new TreeSet() will order the elements;
s1.add("Program");
s1.add("Creek");
s1.add("Java");
s1.add("Java");
s1.add("tutorial");
System.out.println("Set Elements");
System.out.print("\t" + s1 + "\n");
Map<String, String> m1 = new HashMap<String, String>(); // or new TreeMap() will order based on keys
m1.put("Windows", "2000");
m1.put("Windows", "XP");
m1.put("Language", "Java");
m1.put("Website", "programcreek.com");
System.out.println("Map Elements");
System.out.print("\t" + m1);
輸出結(jié)果:
ArrayList Elements
[Program, Creek, Java, Java]
LinkedList Elements
[Program, Creek, Java, Java]
Set Elements
[tutorial, Creek, Program, Java]
Map Elements
{Windows=XP, Website=programcreek.com, Language=Java}
(轉(zhuǎn))http://www.hollischuang.com



