public ArrayList(Collection c)方法的一個注釋 c.toArray might (incorrectly) not return Object[] (see 6260652)


/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 * 使用集合類對象初始化ArrayList
 *
 * @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;
    //剛才看了一眼這個toArray方法,確實有時候返回的不是Obdect[],
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, size, Object[].class);
}

 


以上為ArrayList的一個構造函數,在里面有一句
c.toArray might (incorrectly) not return Object[] (see 6260652)
這個注釋,參見bug6260652,java的bug官網http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6260652


問題就在這兒了,List<String> strList= Arrays.asList("abc");返回的結果是String[],不謝。。。

以下為測試代碼

1   public static void main(String[] args) {
2         List<String> stringList= Arrays.asList("test");
3         Object[] strList=stringList.toArray();
4         System.out.println(strList.getClass());
5     }

 

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM