容器涉及到并发的一点收集

94 篇文章 0 订阅
0 篇文章 0 订阅

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里很少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值