Prefer Collections over older classes

来源:互联网 发布:同步看电视的软件 编辑:程序博客网 时间:2024/05/18 02:32

http://www.javapractices.com/topic/TopicAction.do?Id=39

Most programmers prefer the Java Collections Framework to arrays, Vector, and Hashtable, for the following reasons:

  • the intent of the Collections Framework is to replace the older, less comprehensive tools
  • synchronization can be easily controlled (while Hashtable and Vector are always synchronized)
  • immutability can be easily controlled
  • search and sort algorithms are ready-made
  • the type of a reference to a Collection can be generic, while underlying implementation can be easily changed
  • arrays are of fixed size, and are more error prone - off-by-one errors with array indexes have always been a fruitful source of error
  • Arrays.asList may be used to pass an array to a method expecting a Collection or a List
  • Collection.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
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");  }} 


0 0
原创粉丝点击