This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
                                
                                    (4个答案)
                                
                        
                2年前关闭。
            
        

LinkedList<CasosPossiveis> casos = new LinkedList<>();
CasosPossiveis objeto = new CasosPossiveis();

for (int i=0; i<10; i) {
    //modifying objeto values here
    casos.add(objeto);
}


每当我修改objeto值时,casos上的每个位置也会被修改。我相信casos.add(objeto)使用的是objeto的引用。我需要的是每次我向casos添加新对象并修改objeto时,都不会修改已经添加到列表中的值。

范例:

objeto.setId=1;
casos.add(objeto);
objeto.setId=2;
casos.add(objeto);


当我打印casos时我期望什么:

1, 2


我的代码引人注目:

2, 2

最佳答案

您要在每个casos中添加相同的对象,请尝试以下操作:

  LinkedList<CasosPossiveis> casos = new LinkedList<>();

     for (int i=0; i<10; i) {
     CasosPossiveis   objeto = new CasosPossiveis();
     //modifying objeto values here
      casos.add(objeto);
 }

关于java - Java中LinkedList添加方法的使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47487641/

10-11 03:35