开发者

When is it better to use a vector than an array and vice versa in java?

When is it better to use a vector than an array and vice versa in java? and开发者_开发问答 why?


Vector: never, unless an API requires it, because it's a class, not an interface.

List: this should be your default array-like collection. It's an interface so anything can be a List if it needs to. (and there are lots of List implementations out there e.g. ArrayList, LinkedList, CopyOnWriteArrayList, ImmutableList, for various feature sets)

Vector is threadsafe, but so is the Collections.synchronizedList() wrapper.

array: rarely, if required by an API. The one other major advantage of arrays is when you need a fixed-length array of primitives, the memory space required is fairly compact, as compared to a List<Integer> where the integers need to be boxed into Integer objects.


A Vector (or List) when you don't know before hand how many elements are going to be inserted.

An array when you absolutely know what's the maximum number of elements on that vector's whole life.

Since there are no high performance penalties when using List or Vector (any collection for that matter), I would always chose to use them. Their flexibility is too important to not be considered.

Nowadays I only use arrays when I absolutely need to. Example: when using an API that requires them.


First off ArrayList is a faster implementation than Vector (but not thread safe though).

Arrays are handy when you know the length beforehand and will not change much (or at all).


When declaring a method, use List.

Do not use Vector, it's an early part of the JDK and was retrofitted to work with Collections.

If there's a very performance-sensitive algorithm, a private array member can be helpful. If there's a need to return its contents or pass them to a method, it's generally best to construct an object around it, perhaps as simple as Arrays.asList(thePrivateArray). For a thread-safe list: Collections.synchronizedList(Arrays.asList(thePrivateArray)). In order to prevent modification of the array contents, I typically use Collections.unmodifiableList(Arrays.asList(thePrivateArray)).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜