天天看点

vector是什么 java_java数据结构中,什么情况下用Vector,什么情况下用ArrayList呢?...

1.楼上说的都在理,其实最主要的原因是实际开发中的需求决定的。

2.我先整理一下楼上各位答主的答案:

①Vector所有方法都是同步,有性能损失。

②Vector早期版本出现的。

③Vector初始length是10 超过length时 以100%比率增长,相比于ArrayList更多消耗内存。

这些答案分析的都到位,但是这里我更想从实际应用的角度来谈谈:

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Vector 把集合的每个操作(增删改查)都加上了锁,而这锁从来都不是必须的。

通常的,在实际开发中,我们更多的是通过锁定一系列的操作来实现线程安全的,也就是说将许多需要同步的资源放到一起(比如放到同一个方法或者代码块)来加锁保证线程安全,这样将需要保证线程安全的资源进行规整,一起同时用一把锁。例如:

synchronized void test{

a.set();

v.add(person);

b.set();

// 以上三个操作都需要保证线程安全。

}//v代表vector对象

如果多个Thread 并发执行该方法,可以得知

明明方法本身已经加锁,已经能够保证线程安全了,所以此处根本不需要vector的自己再进行方法的加锁了。如果这种情况下还要使用vector的话,就会造成锁额外开销。

所以这里更适合ArrayList。

2.如果对集合进行 保证线程安全的遍历的话,Vector自身无法保证遍历安全,也得额外加锁,和ArrayList一样。

总结:Vector会在你不需要进行线程安全的时候,强制给你加锁,导致了额外开销,所以慢慢被弃用了。

这是我的理解,如果哪里不到位,请各位狠心指正,以免误导别人。

题主不明白的话,可以继续追问我。