【问题标题】:Comparison of an old variable to a new one after some calculations经过一些计算后将旧变量与新变量进行比较
【发布时间】:2015-12-16 09:00:06
【问题描述】:
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 循环之后读取它。这应该可行,但还有其他解决方案吗?

【问题讨论】:

  • 显示你的for循环的代码,以及两个变量的比较。
  • 显示你没有伪代码的代码,方便排查
  • 好吧,我的猜测是,您将对象与 == 而不是 .equals() 进行比较
  • 听起来使用的类型是“引用类型”,所以variable1variable2value_of_A 总是引用同一个对象。所以请发布你的真实代码(就像 Eran 建议的那样)。
  • @nafas,您能否在审阅过程中多加注意,避免批准糟糕的编辑建议?谢谢。

标签: java variables encapsulation


【解决方案1】:

我猜你的问题是你正在使用对象,并且在 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

【讨论】:

  • 嗨,这听起来很敏感,但不知道如何实现它。可以举个例子吗?
  • 示例已添加,请查看
【解决方案2】:

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

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

那么o1o2 指向同一个对象,因此在o1 中所做的更改也会影响o2。这称为Aliasing

为了比较两个不同的对象,例如,您可以在 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,它们不再相互影响。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 2020-10-20
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多