ArrayList中的构造函数问题

来源:互联网 发布:淘宝客新手如何玩鹊桥 编辑:程序博客网 时间:2024/06/08 00:48

ArrayList中的构造函数问题

原创 2017年02月10日 15:15:35

今天无聊想来看看ArrayList的实现源码,发现创建ArrayList对象时,先定义的ArrayList对象必须指定类型,即这样:

[java] view plain copy
  1. //对的  
  2. ArrayList<String> list = new ArrayList<String>();  
  3.   
  4. //错误的  
  5. ArrayList() list2 = new ArrayList<String>();  
  6.   
  7. ArrayList(20) list3 = new ArrayList<String>();  

但是你会发现ArrayList的源码中有三个构造函数:但是为什么却只能定义其中一个构造函数的对象呢?下面是ArrayList的三个构造函数源码

[java] view plain copy
  1. public ArrayList(int initialCapacity) {  
  2.     super();  
  3.     if (initialCapacity < 0)  
  4.         throw new IllegalArgumentException("Illegal Capacity: "+  
  5.                                            initialCapacity);  
  6.     this.elementData = new Object[initialCapacity];  
  7. }  
  8.   
  9. /** 
  10.  * Constructs an empty list with an initial capacity of ten. 
  11.  */  
  12. public ArrayList() {  
  13.     this(10);  
  14. }  
  15.   
  16. /** 
  17.  * Constructs a list containing the elements of the specified 
  18.  * collection, in the order they are returned by the collection's 
  19.  * iterator. 
  20.  * 
  21.  * @param c the collection whose elements are to be placed into this list 
  22.  * @throws NullPointerException if the specified collection is null 
  23.  */  
  24. public ArrayList(Collection<? extends E> c) {  
  25.     elementData = c.toArray();  
  26.     size = elementData.length;  
  27.     // c.toArray might (incorrectly) not return Object[] (see 6260652)  
  28.     if (elementData.getClass() != Object[].class)  
  29.         elementData = Arrays.copyOf(elementData, size, Object[].class);  
  30. }  

原因就在于其中有一个构造函数中引入了泛型。Java的泛型使用方法是:如果你在一个函数中引入泛型参数,那么就必须将此函数声明为泛型函数,

ArrayList这个例子是因为他在构造函数中使用了泛型参数,然后直接将这个ArrayList定义为泛型类,所以就不必要再将构造函数声明为泛型函数了,

所以你在定义ArrayList对象时就必须指定类型。这就是为什么无法使用其他构造函数定义对象的原因,因为ArrayList这个类已经直接声明为泛型类了。

原创粉丝点击