链接列表非常奇怪删除

时间:2014-11-08 03:14:15

标签: java variables linked-list

我有一个小的java应用程序,它将执行一些数学函数。无论如何,我有这个代码,我在创建点并将它们添加到另一个结构,所以我可以稍后使用这些值。这是代码

/*for the sake of the example, this part is fine. these two variables are filled
 earlier but this is how they are initialized */
LinkedList<Point> col = new LinkedList<Point>();
LinkedList<Point> row = new LinkedList<Point>();
/* Issue area below */
LinkedList<Point> added = new LinkedList<Point>();
while(!col.isEmpty()){
    LinkedList<Point> tempRow = row;
    while(!tempRow.isEmpty()){
        added.add(new Point(col.getFirst().x,tempRow.getFirst().y));
        tempRow.remove();
    }
    col.remove();
}

当此代码运行时,行tempRow.remove()也以某种方式从实际行中删除。这对我没有意义,因为我已经创建了它的局部变量temp并调用了THAT实例变量。有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:2)

我认为你误解了以下一行的影响

LinkedList<Point> tempRow = row;

这不会创建一个全新的列表。这只会为row创建一个名为tempRow的别名。对一个的任何修改也会影响另一个。

你可以做的是创建一个新的LinkedList,然后从行添加所有内容。

LinkedList<Point> tempRow = new LinkedList<Point>(row);

这样tempRow将是一个新列表,将包含行中的所有点。