`

HashTable、HashMap、Vector、ArrayList之间的区别

    博客分类:
  • J2SE
阅读更多

 

所有都是Collection (总接口)
Array
有多少元素是确定的,比如足球队上场的队员有11 名,是固定的,就用array
ArrayList
是不固定的,比如用sql 查询数据库,不知道有多少记录返回,用arraylist.
Enumeration
是用来一个一个列举Collection 的元素的,但java2 后被Iterator 替代。
Hashtable
用在比如你想查中国队的10 号是谁,首先put(new Interger(10),new String(“ 海东”)) ,再String name=get(new Interger(10)); 对于简单的key--value 对来说,hashtable 很有用,建议hashmap.

HashMap/Hashtable Vector/ArrayList 都是放一组对象,一个是用key object 来定位element, 另一个是用index 定位element.
推荐使用HashMapArrayList 的原因一样,因为他们不是Synchronized, 因为不需要obtain lock each time, 它们相对快很多。Synchronized 在最底层是没有意义的,在这里不想多讲。
我本人更加推荐是用LinkedList 而不是ArrayList. 因为在更多的时候,我们很少真的从一个List 里拿出某一个element ,相对的,遍例整个List 的情况最多,在这种情况下用Iterator 是最高效的。
Vector
是一个一维的容器。HashTableHashMap 都是二维的。
和数组的区别是hash…… 不用向数组那样事先定义长度。而可以随意追加。它是key和value对应的。用key作为检索。
HashTable
Vector 都是Synchronized 都是旧的Java 平台的集合类,ArrayListHashMap 由于少了Synchronized 的开销,速度比较快。一般不牵涉到线程之间数据共享的问题都用ArrayListHashMap 吧,当然也可以用LinkedList ,用 listIterator 来遍历.
HashTable
HashMap
上面两个用起来差不多,不过建议使用HashMap ,因为hashtable 被淘汰了

Vector ArrayList
Vector
ArrayList 慢,是因为vector 本身是同步的,而arraylist 不是
所以,没有涉及到同步的推荐用arraylist.

jdk 关于vector 说明的第3 段:
As of the Java 2 platform v1.2, this class has been retrofitted to implement List, so that it becomes a part of Java's collection framework. Unlike the new collection implementations, Vector is synchronized.

显然,vector 是同步的,楼主如不想自己实现同步的话,还是将就用一下vector
既然大家都讲到了同步,那么也稍微谈一下,同步了的HashtableVector 真的那么有用吗?真的如果用了socalled thread-safe Hashtable and Vector 程序代码就不用再同步了吗?
这个例子(Vector vec; Object element;)
if (!vec.contains(element))
   vec.add(element);
这段代码可以不同步吗?不可以,context switch might take place right after you do the containg check.
所以,在程序中还是需要:
synchronized (vec)
{
  if (!vec.contains(element))
   vec.add(element);
}
这样Synchronized Vector 比起没有Synchronized ArrayListLinkedList 来说一点好处都没有了。
再谈ArrayListLinkedList
ArrayList
的缺点是,当the underlying Array reaches the maximum capacity, 一个新的双倍长的array has to be initialized, 紧跟着的是Array Copy, 很慢。同样,remove1/4length 时,array shrinks by creating a new shorter array and array copy all elements. 所以,如果你要用的List 打算常常改变,绝对不应该用ArrayList, 应改为LinkedList.
LinkedList
的缺点是当去取某个indexed element 时,必须做一次遍历。但是,这种情况我发现在real life project 里很少。

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics