Prefer Collections over older classes

Most programmers prefer the Java Collections Framework to arrays, Vector, and Hashtable, for the following reasons: Since JDK 1.5, a strong case can be made that Collections should almost always be preferred over arrays.

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");
  }
} 



See Also :
Choosing the right Collection
Avoid basic style errors
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -