我有一个Path类,我认为它是不可变的.在另一个名为Test的类中,我有一个Path对象的最终引用.
然而,在构造函数和getter方法之间,即使Path对象是不可变的并且引用是final,Path对象也会更改.我知道这一点,因为Path中int数组节点的长度从构造函数变为getter.看起来这个对象完全是一个完全不同的对象.
我的程序是多线程的,但我已尝试使用单个线程,但没有解决问题.
这是不可变的Path类
public class Path implements Iterable<Point> {
private final int[] nodes;
private final double distance;
public Path(Scenario scenario, int gateway, int sensor){
this.scenario = scenario;
nodes = new int[2];
nodes[1] = -gateway - 1;
nodes[0] = sensor;
distance = scenario.DISTANCE_GATEWAY_SENSOR[gateway][sensor];
}
public Path(Path base, int newSensor){
scenario = base.scenario;
//Copy the old path. These are rigid structures so that we do not need to deep copy
nodes = new int[base.nodes.length + 1];
for(int i = 0; i …Run Code Online (Sandbox Code Playgroud)