[英]ArrayList copy all the above items when I add a new element? Java
我有以下幾點:
ArrayList<int[]> lista = new ArrayList<int[]>();
int[] posible_mov = new int[2];
posible_mov[0] = 0;
posible_mov[1] = 0;
lista.add(posible_mov);
posible_mov[0] = 1;
posible_mov[1] = 1;
lista.add(posible_mov);
好吧,如果我使用 arraylist 進行演示並獲取所有元素方法,則在兩種情況下都會顯示:
列表.get(0) => 1, 1 列表.get(1) => 1, 1
為什么?
您將對posible_mov
的引用添加到lista
。 這就是為什么你總是打印 1,1 的原因,因為在代碼的最后一部分你給posible_mov
賦值 1。你可以嘗試改變賦值的順序,你會看到你將打印 0,0。
如果要添加多個對象,而不是引用它們,則可以執行以下操作:
int[] posible_mov = new int[2];
posible_mov[0] = 0;
posible_mov[1] = 0;
lista.add(posible_mov);
posible_mov = new int[2]
posible_mov[0] = 1;
posible_mov[1] = 1;
lista.add(posible_mov);
您的參考變量只是覆蓋以前存儲的值。
因此,為了避免這種情況發生,您可以創建另一個對象而不引用它們,或者如果要同時保留兩個數組,則創建另一個具有不同名稱的數組。 在第一個 lista.add() 函數之后,您可以添加以下內容之一:
posible_mov = new int[2];
或者
int[] posible_mov_1 = new int[2]; //Use this variable name for further operations on this object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.