链表被覆盖[重复]

问题描述 投票:-1回答:1

我有以下伪代码

package forum;

import java.util.LinkedList;

public class Forum {

public static void main(String[] args) {

    Coordinates POS = new Coordinates(0., 0.);

    LinkedList<Coordinates> LIST = new LinkedList<>();

    LIST.add(POS);
    System.out.println(POS.x + "\t" + POS.y);

    for(int i=0; i<10; i++) {

        POS.add(i+10, 0);
        LIST.add(POS);            
        System.out.println(POS.x + "\t" + POS.y);

    }

    System.out.println("------------------");

    for(Coordinates c : LIST) {
        System.out.println(c.x + "\t" + c.y);
    }


}

private static class Coordinates {

    public double x = 0.;
    public double y = 0.;

    public Coordinates(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public void add(double xp, double yp) {
        this.x+=xp;
        this.y+=yp;
    }
}

}

循环变量'POS'不断更改并添加到我的列表中。不幸的是,LIST的所有先前值也被更改。结果是:

10.0    0.0
21.0    0.0
33.0    0.0
46.0    0.0
60.0    0.0
75.0    0.0
91.0    0.0
108.0   0.0
126.0   0.0
145.0   0.0
------------------
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
145.0   0.0
BUILD SUCCESSFUL (total time: 0 seconds)

LIST是否填充有相同的实例,或者它始终指向相同的引用吗?

如何添加要保存和操纵的值?

java linked-list overwrite
1个回答
0
投票

您将继续更改单个坐标实例的值。您不断添加相同的内容。您在“ POS”中输入的最后一个值就是您看到的值。每次添加一个值时,都需要创建一个新的Coordinate实例。

for (int i = 0; i < 10; i++) {
    Coordinates p = new Coordinates(POS.x, POS.y);
    p.add(i + 10, 0);
    list.add(p);
    POS = p;
    System.out.println(POS.x + "\t" + POS.y);   
}

现在将打印程序。

0.0     0.0
10.0    0.0
21.0    0.0
33.0    0.0
46.0    0.0
60.0    0.0
75.0    0.0
91.0    0.0
108.0   0.0
126.0   0.0
145.0   0.0
------------------
0.0     0.0
10.0    0.0
21.0    0.0
33.0    0.0
46.0    0.0
60.0    0.0
75.0    0.0
91.0    0.0
108.0   0.0
126.0   0.0
145.0   0.0
© www.soinside.com 2019 - 2024. All rights reserved.