【问题标题】:How to make static variable of object A immutable to state changes on object B如何使对象 A 的静态变量对对象 B 的状态更改不可变
【发布时间】:2013-10-11 08:02:02
【问题描述】:

如果我有一些简单的课程,例如。问题是此类的实例 B 会影响实例 A 的j

public class Tester {
    private static int j;

    public Tester() {
    }

    public void setJ(int i){
        this.j = i;
    }

    public int getJ() {
        return j;
    }
}

在我的实际应用程序中,j 必须是 static(所以 private static 类可以使用它)。但是,当我在上面的示例中设置static 时遇到问题。如果我们创建这个类的两个单独的实例,我可以显示问题:

Tester testOne = new Tester();
Tester testTwo = new Tester();

testOne.setJ(1);
testTwo.setJ(2);

System.out.println(testOne.getJ()); //returns 2

然后通过在testTwo 中设置静态变量,它会覆盖我之前为testOne 中的静态变量设置的内容。如果我要删除static,那么j 相对于testTwo.setJ(2) 将是不可变的,但我不能拥有这个。

我该如何解决这个问题?

【问题讨论】:

  • 嗯,是的。这就是static 所做的。

标签: java variables static scope immutability


【解决方案1】:

这不是错误,这是正确的行为。如果你真的需要你刚才解释的smtg,你可以试试这样:

public class Tester {
    private static int j;
    private boolean jWasSet;

    public Tester() {
    }

    public void setJ(int i){
        if (!jWasSet) {
            this.j = i;
            jWasSet = true;
    }

    public int getJ() {
        return j;
    }
}

【讨论】:

  • 如果你想重新设置呢?!
  • 从作者的角度来看:“它覆盖了我之前为testOne中的静态变量设置的内容”,我理解他不希望在第一次设置后更改它=)
【解决方案2】:

如果一个变量是静态的,那么如果你改变一次,它就会在任何地方反映出来 当您执行 testOne.setJ(1); 时,变量设置为 1,但您再次调用 testTwo.setJ(2);,因此变量再次设置为 2,所以最终您得到 2

在我的实际应用程序中,j 需要是静态的(因此私有静态类可以使用它)。 您可以创建一个对象,然后调用实例变量而不将其设为静态

【讨论】:

    【解决方案3】:

    静态字段对类的所有实例都是通用的。在您的情况下,由于 j 是静态的,因此它对于您为该类创建的任意数量的实例都是通用的。 1 个实例所做的更改将反映在另一个实例中。

    这样看。

    There is a static `j` - since its static, it'll be initialized to 0 by default.
    j = 0  // initially
    
    testOne.setJ(1) // This makes j = 1
    j = 1 // Now
    
    testTwo.setJ(2) // This makes j = 2, since j is shared by all instances of your class(property of static fields)
    j = 2 // Finally
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 1970-01-01
      • 2017-12-07
      • 2015-01-30
      相关资源
      最近更新 更多