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

来源:互联网 发布:十字军之王2优化补丁 编辑:程序博客网 时间:2024/06/03 20:07

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

Java综合 
测试代码如下: 
Java代码  收藏代码
  1. List<String> l = new ArrayList<String>(2);  
  2. l.add("444");  
  3. l.add("aaa");  
  4. l.add("xxxx");  
  5. for (String s : l) {  
  6.     System.out.println(s);  
  7. }  

输出结果: 
Java代码  收藏代码
  1. 444  
  2. aaa  
  3. xxxx  


疑问:为什么会打出"xxxx"呢?来看下源码 
Java代码  收藏代码
  1.    /** 
  2.     * Constructs an empty list with the specified initial capacity. 
  3.     * 
  4.     * @param   initialCapacity   the initial capacity of the list. 
  5.     * @exception IllegalArgumentException if the specified initial capacity 
  6.     *            is negative 
  7.     */  
  8.    public ArrayList(int initialCapacity) {  
  9. super();  
  10.        if (initialCapacity < 0)  
  11.            throw new IllegalArgumentException("Illegal Capacity: "+  
  12.                                               initialCapacity);  
  13.         //这里已经初始化了容器量  
  14. this.elementData = (E[])new Object[initialCapacity];  
  15.    }  


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



下面是测试数组的: 
Java代码  收藏代码
  1. String[] strArr = new String[2];  
  2. strArr[0] = "11";  
  3. strArr[1] = "22";  
  4. strArr[2] = "33";  
  5. for (String ss : strArr) {  
  6.     System.out.println(ss);  
  7. }  


会报异常 


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

原创粉丝点击