ArrayList.toArray()返回的不是真實的動態數組

 

 1、ArrayList真實的動態 數組爲 

transient Object[] elementData;

 下面是ArrayList.toArray()的函數,返回的是一個新的數組,該數組包含了這個集合裏的內容

 /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     * <p>The returned array will be "safe" in that no references to it are      
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *    返回一個安全的數組,這個數組沒有被該list維護對它的引用。(換句話說,這個方法返回了一個新的數組)
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list in
     *         proper sequence
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

 

=============================注意:不要這樣使用=============================

List<Integer> alist= new ArrayList<Integer>();
		alist.add(1);
		alist.add(5);
		alist.add(2);
		Arrays.sort(alist.toArray());//不會起到排序作用

如果需要排序請使用

Collections.sort(alist);

複雜類型用

List<MakeSql> blist= new ArrayList<MakeSql>();
		blist.sort(new Comparator<MakeSql>() {
			@Override
			public int compare(MakeSql o1, MakeSql o2) {
				// TODO Auto-generated method stub
				return 0;
			}
			
		});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章