JAVA集合框架

1.JAVA集合框架图

2.大致讲解java集合的体系结构

 List、Set、Map是这个集合体系中最主要的三个接口。

 List和Set继承自Collection接口

 Set不允许元素重复.HashSet和TreeSet是两个主要的实现类

 List有序且允许元素重复。ArrayList、LinkedList和Vector是三个主要的实现类。

 Map也属于集合系统,但和Collection接口不同。Map是key对value的映射集合,其中key列就是一个集合。key不能重复,但是value可以重复。HashMap、TreeMap和 Hashtable是三个主要的实现类。

3. ArrayList和Vector有什么区别?

ArrayList的add方法:
public
boolean add(E e) { ensureCapacityInternal(size + 1); elementData[size++] = e; return true; }
Vector的add方法:
public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; }
结论: Vector是线程同步的(synchronized),ArrayList是非同步的
所以在性能上: ArrayList的优于Vector

 4. HashTable和HashMap的区别

最大的区别是: Hashtable的方法是线程安全(synchronized)的,HashMap不是

HashMap中,null可以作为键,这样的键只有一个。可以有一个或多个键所对应的值为null。当get()方法返回null值时,即可以表示HashMap中没有该键,也可以表示该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键,而应该用containsKey()方法来判断。

HashTable中,不允许null键和null值

Hashtable<String, String> hashtable = new Hashtable<String,String>();
hashtable.put(null, null);
hashtable.put(null, "123");
hashtable.put("123", null);

上面三句任何一句都会报java.lang.NullPointerException异常

Map<String, String> hashmap = new HashMap<String,String>();
hashmap.put(null, null);
hashmap.put(null, "123");
hashmap.put("123", null);
        
System.out.println(hashmap.size());
System.out.println(hashmap.get(null));
System.out.println(hashmap.get("123"));

上面的代码运行结果是:

 2
 123
 null

5. HashMap从非线程安全变身线程安全

Hashtable中的方法是同步的,而HashMap中的方法在缺省情况下是非同步的。即是说,在多线程应用程序中,不用专门的操作就安全地可以使用Hashtable了;而对于HashMap,则需要额外的同步机制。

Map<String,String> map = new HashMap<String,String>();
Map<String,String> mapSync = Collections.synchronizedMap(map);

通过上面的代码,HashMap摇身一变,成为了线程安全的。通过java.util.Collections这个集合工具类的静态方法synchronizedMap就可以实现。

查看Collections的synchronizedMap方法的源码可以发现,它其实就是重写了Map的get、set、equals、hashCode等方法,在方法前面加上了synchronized关键字,其实还是调用的HashMap的方法。

6. List从非线程安全变身线程安全

Vector是线程同步的(synchronized),ArrayList是非同步的,既然HashMap都能变身,为什么List不行呢
List<String> list = new ArrayList<String>();
List<String> listSync = Collections.synchronizedList(list);

通过java.util.Collections这个集合工具类的静态方法synchronizedList就可以实现List为身为线程安全的。它的源代码里面的处理方式和synchronizedMap方法是一样的,重写List的方法,在方法前面加上synchronized关键字。

posted @ 2015-04-15 11:11  jerry心  阅读(355)  评论(0编辑  收藏  举报