此程序用于测试 :每次for循环内重新定义一个Integer数组,赋值后加入arrayList。由于下一次的Integer对象重新定义,原来的对象是否会被释放?
解答:不会,因为原对象仍被引用(被arrayList指向),不会释放空间。所以每次循环重新定义一个对象对arrayList内的元素无影响。
源程序:
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 4 public class Test { 5 public static void main(String[] args) { 6 ArrayList<Integer[]> arrayList = new ArrayList<>(); 7 for (int i = 0; i < 5; i++) { 8 Integer[] eles = new Integer[5]; 9 10 for (int j = 0; j < 5; j++) { 11 eles[j] = i; 12 } 13 arrayList.add(eles); 14 System.out.println("array " + i); 15 System.out.println(Arrays.toString(arrayList.get(i))); 16 System.out.println(); 17 } 18 19 } 20 }
输出:
总忘记这两个点,记录一下。
声明ArrayList(动态数组)时,不用指定空间大小。
arrayList.size()返回的是list内的元素个数,此处没有加入元素,不能使用。
错误:
size()源代码: