所有的东东都是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.
推荐使用HashMap和ArrayList的原因一样,因为他们不是Synchronized,因为不需要obtain lock each time,它们相对快很多。Synchronized在最底层是没有意义的,在这里不想多讲。
我本人更加推荐是用LinkedList而不是ArrayList.因为在更多的时候,我们很少真的从一个List里拿出某一个element,相对的,遍例整个List的情况最多,在这种情况下用Iterator是最高效的。
Vector是一个一维的容器。HashTable、HashMap都是二维的。
和数组的区别是hash……不用向数组那样事先定义长度。而可以随意追加。它是key和value对应的。用key作为检索。
HashTable和Vector都是Synchronized都是旧的Java平台的集合类,ArrayList和HashMap由于少了Synchronized的开销,速度比较快。一般不牵涉到线程之间数据共享的问题都用ArrayList和HashMap吧,当然也可以用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
既然大家都讲到了同步,那么也稍微谈一下,同步了的Hashtable和Vector真的那么有用吗?真的如果用了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 ArrayList和LinkedList来说一点好处都没有了。
再谈ArrayList和LinkedList:
ArrayList的缺点是,当the underlying Array reaches the maximum capacity,一个新的双倍长的array has to be initialized,紧跟着的是Array Copy,很慢。同样,remove到1/4length时,array shrinks by creating a new shorter array and array copy all elements.所以,如果你要用的List打下常常改变,绝对不应该用ArrayList.
LinkedList的缺点是当去取某个indexed element时,必须做一次遍历。但是,这种情况我发现在real life project里很少。

posted on 2006-08-08 11:17  EasyWriter  阅读(5983)  评论(3编辑  收藏  举报