日期:2014-05-20  浏览次数:20749 次

ArrayList源码,这点看不懂
Java code
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient E[] elementData;

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * 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];  //这里为什么可以这样,E类型肯定是Object的  
                                 //子类,父类怎么可以转换子类,要可以转换,得父类最开始的类型就是它要转换
                                      //成子类的类                型才行啊
    }



//模仿上面的源代码,测试
Java code
public class TestSet {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String [] strs = null;
        
        strs =(String[]) new Object[5];//一运行报java.lang.ClassCastException错,这里肯定不可以这样转换
        System.out.println(strs.length);
    }

}


------解决方案--------------------
(E[])new Object[initialCapacity];

这个你可以认为纯粹为了让编译器通过罢了,在实际的Class文件中,并没有对这个Object作出真正的类型转换,elementData仍然是Object[]而不是String[]