java - Java 中的最终和不可变变量更改

标签 java variables immutability final

我有一个 Path 类,我认为它是不可变的。在另一个名为 Test 的类中,我有一个对 Path 对象的最终引用。

然而,在构造函数和 getter 方法之间,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 < base.nodes.length; i++)
                nodes[i + 1] = base.nodes[i];

        nodes[0] = newSensor;
        distance = base.distance + scenario.DISTANCE_SENSOR_SENSOR[newSensor][nodes[1]];
    }

    public Path(Scenario scenario, int[] nodes, boolean isSensor, double distance){
        this.scenario = scenario;
        this.distance = distance;
        this.nodes = Arrays.copyOf(nodes, nodes.length);

        if(!isSensor)
            for(int i = 0; i < this.nodes.length; i++)
                this.nodes[i] = -this.nodes[i] -1;
    }

    @Override
    public Iterator<Point> iterator() {
        return new PointIterator();
    }

    public class PointIterator implements Iterator<Point>{

        private int next = -1;

        @Override
        public boolean hasNext() {
            return next + 1 < nodes.length;
        }

        @Override
        public Point next() {
            int p = nodes[++next];
            if(p >= 0)
                return scenario.SENSOR_LOCATION[p];
            return scenario.CS_LOCATION[-p - 1];
        }

        @Override
        public void remove() {
            throw new IllegalAccessError("This method is not    supported");
        }

    }

}

这是 Test 类(最后引用了 Path 类)

public class Test {

    private final Path gatewayTour;

    public Test(Scenario scenario, boolean[] chosenGateway){
        distanceFitness = 0;
        Point current = scenario.SINK_LOCATION;
        boolean visited[] = new boolean[scenario.CONFIG.NUM_CS];
        int nextGateway;

        LinkedList<Integer> order = new LinkedList<>();

        do {
            double minimumDistance = Double.MAX_VALUE;
            nextGateway = -1;
            for(int i = 0; i < scenario.CONFIG.NUM_CS; i++)
                if(!visited[i] && CHOSEN_GATEWAYS[i] && scenario.CS_LOCATION[i].isCloserThan(minimumDistance, current)) {
                    nextGateway = i;
                    minimumDistance = scenario.CS_LOCATION[i].distance(current);
                }

            if(nextGateway >= 0) {
                distanceFitness += minimumDistance;
                visited[nextGateway] = true;
                order.add(nextGateway);
                current = scenario.CS_LOCATION[nextGateway];
            }
        } while(nextGateway >= 0);

        int path[] = new int[order.size()];
        Iterator<Integer> it = order.iterator();
        for(int i = 0; i < order.size(); i++)
            path[i] = it.next().intValue();

        gatewayTour = new Path(scenario, path, false, distanceFitness);
    }

    public Path getGatewayTour(){
        //Here, the gatewayTour object has changed and does not have the same content as in the constructor
        return gatewayTour;
    }
 }

我的程序中是否有任何允许对象更改的内容?我会更精确:是否有任何东西允许 Path 类中的 int 数组“节点”改变长度?因为这是真正的问题。

[编辑]:我的测试有缺陷,这让我相信我的“节点”数组的值发生了变化。感谢所有指出我的代码缺陷或可能改进的人。

我会接受 AlexR 的回答,因为他指出可以更改最终数组中的单个元素;一些我不知道但有助于解决问题的东西。

最佳答案

Word final 表示不能更改标有该单词的引用。这并不意味着引用的对象不能更改。

这意味着通过更改其字段来更改 Path 的实例是没有问题的。是的,你是对的,你的领域也是最终的。但是让我们检查一下:

private final int[] nodes;
private final double distance;
private final Scenario scenario;

distance 是一个原语,因此一旦在初始化期间分配,它确实无法更改。 nodes 是一个数组,即对象。数组本身不能更改,即引用引用同一个数组。但是,您可以更改数组的元素。

scenario 也是对象。您还没有在此处发送类 Scenario,但是如果可以更改此类的字段,则可以更改此对象。

关于java - Java 中的最终和不可变变量更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012089/

相关文章:

swing - 使用 openjdk 通过 XMing 转发 X11 session 时,swing 应用程序中的文本字段和区域变得不可编辑

java - 我可以在 xxxx-validation.xml 中为列表配置验证吗?

java - 为什么不允许外部接口(interface)为 HashMap 提供 hashCode/equals?

linux - 使用 sed 和变量剪切日志文件

swift - Unexpected Cannot assign to property 'self' is immutable compile time error IN CLASS

javascript - 在 nodejs 中创建不可变对象(immutable对象)的适当方法

c# - 不可变的集合?

java - 如果用户未授权,Spring Security 显示 404

bash - 变量中的通配符,Shell bash,怎么办?变量=$变量2*

MySQL Date Var 在 if 条件后改变