天天看點

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會在你不需要進行線程安全的時候,強制給你加鎖,導緻了額外開銷,是以慢慢被棄用了。

這是我的了解,如果哪裡不到位,請各位狠心指正,以免誤導别人。

題主不明白的話,可以繼續追問我。