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;
			}
			
		});

 

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