Choosing the right Collection
Avoid basic style errors
Vector,
and Hashtable,
for the following reasons:
Hashtable and Vector
are always synchronized)Collection
can be generic, while underlying implementation can be easily changedArrays.asList
may be used to pass an array to a method expecting a Collection
or a ListCollection.toArray
may be used to convert a Collection to an Object[] or
a T[]Collections.enumeration and
Collections.list may be used to convert between enumerations and collections
Prior to JDK 1.5, the main disadvantage of using collections is that
they always held an Object, and retrieval of their contents required
casting. Casting cannot be checked at compile-time. Arrays, on the other
hand, have the advantage of always being "parameterized" to hold objects
of a specific type (in all versions of the JDK), and this is verified by
the compiler. Thus, in older versions of the JDK, changing from a collection to an array forces one particular
kind of error to appear at compile-time instead of run-time.
One minor advantage of arrays is that they are slightly easier to initialize. However, using
Arrays.asList
makes the difference trivial:
import java.util.*; public final class ArrayInit { /** Initialize arrays and Lists. */ public static void main(String... args){ //Array initializers are compact String[] paintings = {"oil", "watercolour"}; //Build a List using Arrays.asList(T...) //This works for any type, not just for String List<String> languages = Arrays.asList( "urdu", "hindi", "pali", "sanskrit" ); //Build a List in a more verbose way List<String> nicePlaces = new ArrayList<>(); nicePlaces.add("luxembourg gardens"); nicePlaces.add("sea side"); nicePlaces.add("large magellanic cloud"); //this is compact, but the returned list is not modifiable List<Integer> years = List.of(1915, 1925, 1957); //years.add(1984); //fails } }