ArrayList中的构造函数问题,arraylist构造函数
分享于 点击 34983 次 点评:8
ArrayList中的构造函数问题,arraylist构造函数
ArrayList中的构造函数问题
原创 2017年02月10日 15:15:35今天无聊想来看看ArrayList的实现源码,发现创建ArrayList对象时,先定义的ArrayList对象必须指定类型,即这样:
[java] view plain copy
- //对的
- ArrayList<String> list = new ArrayList<String>();
- //错误的
- ArrayList() list2 = new ArrayList<String>();
- ArrayList(20) list3 = new ArrayList<String>();
但是你会发现ArrayList的源码中有三个构造函数:但是为什么却只能定义其中一个构造函数的对象呢?下面是ArrayList的三个构造函数源码
[java] view plain copy
- 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这个类已经直接声明为泛型类了。
相关文章
- 暂无相关文章
用户点评