`
weilJava
  • 浏览: 69100 次
  • 性别: Icon_minigender_1
  • 来自: 南京
文章分类
社区版块
存档分类
最新评论

关于ArrayList的有参数构造的疑问

阅读更多
测试代码如下:
		List<String> l = new ArrayList<String>(2);
		l.add("444");
		l.add("aaa");
		l.add("xxxx");
		for (String s : l) {
			System.out.println(s);
		}

输出结果:
444
aaa
xxxx


疑问:为什么会打出"xxxx"呢?来看下源码
    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param   initialCapacity   the initial capacity of the list.
     * @exception IllegalArgumentException if the specified initial capacity
     *            is negative
     */
    public ArrayList(int initialCapacity) {
	super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
         //这里已经初始化了容器量
	this.elementData = (E[])new Object[initialCapacity];
    }


再看add方法:
    /**
     * Appends the specified element to the end of this list.
     *
     * @param o element to be appended to this list.
     * @return <tt>true</tt> (as per the general contract of Collection.add).
     */
    public boolean add(E o) {
	ensureCapacity(size + 1);  // Increments modCount!!
         //上面测试时参数设为2,这里如果再加应该会越界啊,但是最后缺还add进去了,疑问!!!
	elementData[size++] = o;
	return true;
    }



下面是测试数组的:
		String[] strArr = new String[2];
		strArr[0] = "11";
		strArr[1] = "22";
		strArr[2] = "33";
		for (String ss : strArr) {
			System.out.println(ss);
		}


会报异常


补:在这个问题上我起初理解的有些偏差,一直认为list是一个像现实的一个容器,不妨假设为一个罐子,当它的模板定下来后,那么它的容量是一定的。其实这种理解是有很大的问题,在java中像list、map等这些容器都是可自动扩充的。而对于数组而言才可以认为是罐子,没有自动扩充的功能。问题尽管有些低级,但是也是个人的一个理解过程。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics