/**
-
Created by caoxiaohong on 17/11/8 18:45.
-
测试ArrayList类中的方法: public T[] toArray(T[] a)
*/
public class testCode {
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
/**toArray(T[] a) 参数数组长度<集合ArrayList的size大小
* toArray(T[] a) 操作,新生成一个数组,并作为结果返回.
* 返回结果类型和参数a一致,大小和list(集合ArrayList)一致.
* list中内容不会覆盖原来a中的内容.且a的长度也不会更改
*/
Object[] a1={"qqq","www"};
list.toArray(a1);
for(Object o:a1){
System.out.print(o+",");
}
System.out.println();
System.out.println("a1的长度:"+a1.length);
System.out.println("--------------------------------");
/**toArray(T[] a) 参数数组长度=集合ArrayList的size大小
* toArray(T[] a) 操作,大小和list(集合ArrayList)一致.
* list中内容会覆盖原来a中的内容
*/
Object[] a2={"ggg","bbb","ddd","ccc","vvv"};
list.toArray(a2);
for(Object o:a2){
System.out.print(o+",");
}
System.out.println();
System.out.println("a2的长度:"+a2.length);
System.out.println("--------------------------------");
/**toArray(T[] a) 参数数组长度>集合ArrayList的size大小
* 特别注意:此时,并不会生成一个新的数组,返回结果还是a,但是a中的内容发生了改变.
* 有3处改变:
* (1)a下标为:[0,t.size-1]处的内容被list中的元素覆盖.
* (2)a下标为:[size,size]处的内容被赋值为null.
* (3)a下标为:[size+1,a.length-1]处的内容不改变.
*
* 为什么a下标为[size,size]处的内容被赋值为null?
* 用途:如果调用者知道list内部肯定没有null元素,那么通过为a[size]赋值为null,就能轻松知道原来list的长度.
*/
Object[] a3={"nnn","xxx","zzz","lll","mmm","yyy","ooo"};
list.toArray(a3);
for(Object o:a3){
System.out.print(o+",");
}
System.out.println();
System.out.println("a3的长度:"+a3.length);
System.out.println("--------------------------------");
}
}
If the list fits in the specified array with room to spare
* (i.e.,the array has more elements than the list),the element in
* the array immediately following the end of the collection is set to
* null. (This is useful in determining the length of the
* list only if the caller knows that the list does not contain
* any null elements.)
*
* @param a the array into which the elements of the list are to
* be stored,if it is big enough; otherwise,a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type,but my contents:
return (T[]) Arrays.copyOf(elementData,size,a.getClass());
System.arraycopy(elementData,a,size);
if (a.length > size)
a[size] = null;
return a;
}
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|