欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

ArrayList中的构造函数问题,arraylist构造函数

来源: javaer 分享于  点击 27250 次 点评:16

ArrayList中的构造函数问题,arraylist构造函数


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

		//对的
		ArrayList<String> list = new ArrayList<String>();
		
		//错误的
		ArrayList() list2 = new ArrayList<String>();
		
		ArrayList(20) list3 = new ArrayList<String>();

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

    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this(10);
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

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

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

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



相关文章

    暂无相关文章

用户点评