Prefer Collections over older classes

本文探讨了Java集合框架相较于数组的优势,包括同步控制、不可变性、预定义的搜索和排序算法、引用类型和底层实现的灵活性。还讨论了从集合到数组的转换以及在不同Java版本中使用集合的优点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值