面試的時候也總是問的一個問題,說一下Vector與ArrayList的區別?
這個問題以前沒太注意過,所以查詢資料的時候,看到網上對這個問題的解釋幾乎是相同(應該都是copy的),千篇一律且比較囉嗦。這次找到一個老外的解釋,比較簡單形象,轉載一下,很簡單的。印度阿三寫的,串連地址是
http://javapapers.com/core-java/java-collection/difference-between-vector-and-arraylist-in-java/
有興趣的可以自己去看看。
java.util.Vector came along with the first version of java development kit (JDK). java.util.ArrayList was introduced in java version1.2, as part of java collections framework. As per java API, in Java 2 platform v1.2,vector has been retrofitted to implement
List and vector also became a part of java collection framework.
All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized. All the new implementations of java collection framework is not synchronized.
Vector and ArrayList both uses Array internally as data structure. They are dynamically resizable. Difference is in the way they are internally resized. By default, Vector doubles the size of its array when its size is increased. But, ArrayList increases
by half of its size when its size is increased.
Therefore as per Java API the only main difference is, Vector’s methods are synchronized and ArrayList’s methods are not synchronized.
Vector or ArrayList? Which is better to use in java?
In general, executing a ‘synchronized’ method results in costlier performance than a unsynchronized method. Keeping the difference in mind, using Vector will incur a performance hit than the ArrayList. But, when there is a certain need for thread-safe operation
Vector needs to be used.
Is there an alternate available in java for Vector?
ArrayList can be synchronized using the java collections framework utility class and then ArrayList itself can be used in place of Vector.
When there is no need for synchronized operation and you still look for better performance ‘Array’ can be used instead of ArrayList. But the development is tedious, since it doesn’t provide user friendly methods.
When you use Vector or ArrayList, always initialize to the largest capacity that the java program will need. Since incrementing the size is a costlier operation.
翻譯如下:
java.util.Vector從jdk1.0開始就已經存在了,java.util.ArrayList是從jdk1.2引入的,並且是collection架構的一部分。根據java API,從jdk1.2開始Vector已經被重新定義,它實現了List介面並且Vector也成了collection架構的一部分。
Vector所有的方法都是synchronized(注:是所有的public的非重載方法).但是,ArrayList所有的方法卻不是synchronized所有java collection架構的新的實現方法也都不是synchronized的.
Vector和ArrayList內部都是使用數組做資料結構.他們都是動態改變大小.不同的是他們內部改變大小的方式.預設情況下,Vector大小增長是正常數組大小的一倍,但是,ArrayList大小正常是正常數組的一半.
因此根據java API,Vector和ArrayList主要的不同是,Vector的方法是synchronized,ArrayList的方法不是synchronized.
在java中Vector和ArrayList在使用上哪個更好?
一般而言,使用synchronized的方法和不用synchronized的方法相比,會導致消耗很高的效能.Keeping the difference in mind(不會翻譯),使用Vector會比使用ArrayList消耗更高的效能.但,當需要某種安全執行緒操作時,Vector是必要的.
在java中有沒有可以替代Vector的的東西?
ArrayList可以使用java集合架構的工具類實現synchronized,然後ArrayList就可以替代Vector了.
當不需要synchronized操作時,你仍然可以尋找替代ArrayList的更好實現,但這種開發是無聊的,因為它不能提供給使用者友好的方法.
當你使用Vector或是ArrayList時,他們總是被初始化為最大容量,以方便java程式的使用,因此增長其大小是一項昂貴的操作.