ArrayList源码里面有着一段代码:
public <T> 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, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
我想问一下a[size] = null;这一句有什么作用?为什么要设成NULL?
public <T> 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, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
我想问一下a[size] = null;这一句有什么作用?为什么要设成NULL?
定义一个长度为10的list,list其实就是由一个数组组成的,
这个list的长度为10的话,那么数组中长度10之后的数组对象都要设置为空。
试试下面的看看就知道了List<Integer> list = new ArrayList<Integer>(5);
for(int i = 0; i < 5; i ++){
list.add(Integer.valueOf(1));
}
Integer[] array = new Integer[10];
for(int i = 0; i < array.length; i ++){
array[i] = Integer.valueOf(2);
}
list.toArray(array);
for(Integer value : array){
System.out.println(value);
}