读书人

HashTable、HashMap、Vector、ArrayLi

发布时间: 2012-09-09 09:27:54 作者: rapoo

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

?

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

读书人网 >编程

热点推荐