Java中集合类的关系图谱

Collection 和 Collections

首先要明确的是,Collection 和 Collections是两个不同的概念。Collection是一个接口,所有的集合类(除Map外)都要继承(实现)自该接口。它提供了对集合对象进行基本操作的通用接口方法。Collections是一个包装类,它包含有各种有关集合操作的静态多态方法。(Collections是一个工具类,不能实例化)

Collection家族关系图

一、Vector、LinkedList、ArrayList
区别 http://www.hollischuang.com/archives/1349
  1. VectorArrayList是使用数组实现的,LinkedList是使用链表实现的

2)Vector是线程安全的,LinkedListArrayList不是线程安全的

如果涉及到多线程,那么就选择Vector,如果不涉及到多线程就从LinkedListArrayList中选。 LinkedList更适合从中间插入或者删除(链表的特性)。 ArrayList更适合检索和在末尾插入或删除(数组的特性)。

PS: Collections.synchronizedList(List list)方法也可以用来返回一个线程安全的List。参见SynchronizedList和Vector的区别

Map家族的关系图

二、HashMap、HashTable、ConcurentHashMap

  1. HashMapHashTable都实现了Map接口,ConcurrentHashMap实现了ConcurrentMap接口

  2. HashMapConcurrentHashMap 都继承了AbstractMap类,HashTable继承了Dictionary

3)HashTableConcurrentHashMap是线程安全的,HashMap不是线程安全的。

  1. 当一个线程访问HashTable的同步方法时,其他线程访问HashTable的同步方法时,可能会进入阻塞或轮询状态。

  2. ConcurrentHashMap使用锁分段技术,将数据分成一段一段的存储,给每一段数据配一把锁,当一个线程占用锁访问其中一个段数据的时候,其他段的数据也能被其他线程访问。

如果不涉及到多线程处理的情况,就是用hashMap,因为他的效率比较高。在有并发请求的场景中,如果数据的强一致性比较重要,那么就请使用hashTable,因为ConcurrentHashMap的get,clear,iterator 都是弱一致性的。如果效率要求比较高,那么就使用ConcurrentHashMap,因为他不会像hashTable那样产生阻塞。


关系图谱

代码示例

下面是一个简单的例子来说明一些集合类型:

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);

输出结果:

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}

(转)http://www.hollischuang.com

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容