经过一些计算后将旧变量与新变量进行比较


variable1 = value_of_A;
for loop {
    //some calculations over value_of_A,
    //so it is not anymore the same as in variable1
}
variable2 = value_of_A;

当我比较variable1variable2它们一直都是一样的。我已经尝试了新类,因此 setter 可以存储值、方法、所有类型的变量定义等。到目前为止可能的解决方案:将variable1写入文件,然后在 for 循环后读取它。这应该有效,但是还有其他解决方案吗?

我想你的问题是你正在使用对象,而在 Java 中对象是通过引用传递的。这意味着,你可能有一个对象和两个变量引用它,当你通过第一个引用变量(variable1(更改对象时,第二个引用变量(variable2(现在允许你访问同一个对象,它已经改变了。您的解决方案是在循环中创建一个新对象,并将对该新对象的引用分配给您的variable2,这样您就必须使用对每个对象的单个引用来区分对象。

// suppose this is the class you are working with
public class SomeObject {
    private String nya;
    public SomeObject(String value) {
        nya = value;
    }
    public String getValue() {
        return nya;
    }
    public void changeByValue(int value) {
        nya += "Adding value: " + value;
    }
}
// and here comes the code that changes the object
// we assign the first variable the original object
SomeObject variable1 = someObject;
// but we do not assign the same object to the second one,
// instead we create the identical, but new object
SomeObject variable2 = new SomeObject(someObject.getValue());
for (int i = 0; i < 10; i++) {
    // here we change the second (new) object, so the original stays the same
    variable2.changeValueBy(i);
}
System.out.println(variable1 == variable2);      // false
System.out.println(variable1.equals(variable2)); // depends on implementation

在Java中,当使用对象时,你实际上只是有一个对该对象的引用。这意味着,如果你有这样的东西

SomeObject o1 = new SomeObject();
SomeObject o2 = o1;

然后o1o2指向同一个对象,因此o1所做的更改也会影响o2。这称为别名。

例如,为了

比较两个不同的对象,您可以在for循环中更改对象之前使用对象的副本

// This is the object we want to work on.
SomeObject changing = new SomeObject();
// Copy-Constructor, where you assign the fields of 'changing' to a new object.
// This new object will have the same values as 'changing', but is actually a new reference.
SomeObject o1 = new SomeObject(changing); 
for loop {
    // This operation alters 'changing'.
    someOperationOn(changing);
}
// Again, a copy constructor, if you want to have another, different reference.
SomeObject o2 = new SomeObject(changing);

现在,您有两个对象o1o2,它们不再相互影响。

变量的类型是什么?在我看来,这是一个"按价值"与"按参考"的问题。看看这个问题在这里。本质上,根据变量的类型,后跟计算的"="不会创建新对象。您只需要在内存中多一个对同一对象的引用。

最新更新