ArrayList是否在添加新元素时复制上述所有项目?JAVA
我有以下资料:ArrayList是否在添加新元素时复制上述所有项目?JAVA,java,arrays,arraylist,copy,elements,Java,Arrays,Arraylist,Copy,Elements,我有以下资料: 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 lista=n
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 lista=new ArrayList();
int[]posible_mov=新的int[2];
posible_mov[0]=0;
posible_mov[1]=0;
列表a.add(可移动);
可能的_-mov[0]=1;
可能的_-mov[1]=1;
列表a.add(可移动);
好吧,如果我使用arraylist和get all elements方法来演示这两种情况:
lista.get(0)=>1,1
lista.get(1)=>1,1
为什么? 您将对
posible\u mov
的引用添加到列表a
中。这就是为什么您总是打印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
我认为你需要澄清这个问题。我已经读了三遍了,我仍然不完全确定你在问什么。对不起,我是西班牙人。我不能用英语很好地解释