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).
     *
     * 

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维护对它的引用。(换句话说,这个方法返回了一个新的数组) *

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 alist= new ArrayList();
		alist.add(1);
		alist.add(5);
		alist.add(2);
		Arrays.sort(alist.toArray());//不会起到排序作用

如果需要排序请使用

Collections.sort(alist);

复杂类型用

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

 

你可能感兴趣的:(java)