更改类的所有对象的字段

时间:2017-09-30 20:41:17

标签: java

我有一个带有布尔字段的类,我希望同时只有一个对象的字段为真。

我尝试用静态方法设置所有对象的字段,但是我无法从静态方法到达非静态字段。(我不知道静态背后的逻辑)

    public class ToggleBox
{
   private boolean  selected;

    public ToogleBox()
    {
        selected=false;
    }

    public setOnlyTrue()
    {
        setAllFalse();
        selected=true;
    }
    private static setAllFalse()
    {
        this.selected=false;
    }

}

是否有任何技巧可以执行此操作,还是应该迭代所有类的对象以更改所有字段?

2 个答案:

答案 0 :(得分:2)

我能想到的一个技巧是拥有一个静态成员来保存具有true属性的一个实例的引用:

public class MyClass {
    private static MyClass trueObject = null;

    public void setProperty(boolean value) {
        if (value) {
            trueObject = this;
        } else {
            trueObject = null;
        }
    }

    public boolean getProperty() {
        return trueObject == this;
    }
}

答案 1 :(得分:0)

当您想要使用true创建实例并且已创建true时,这取决于您的要求

一个。将所有其他设置为false,将新设置为true

public class ToggleBox {

    private static List<ToggleBox> listAll = new ArrayList<>();

    private boolean selected;

    public ToggleBox(boolean bool) {
        if (bool)                          // if require true
            for (ToggleBox mo : listAll)
                mo.setSelected(false);     // set all other to false

        listAll.add(this);
        this.selected = bool;
    }

    public void setSelected(boolean bool) { this.selected = bool; }

    @Override
    public String toString() {  return selected + "";  }

    public static void main(String argv[]) {
        ToggleBox m1 = new ToggleBox(true);
        ToggleBox m2 = new ToggleBox(false);
        System.out.println(Arrays.toString(listAll.toArray()));  // [true, false]
        ToggleBox m3 = new ToggleBox(true);
        System.out.println(Arrays.toString(listAll.toArray()));  // [false, false,true]
    }

}

B中。拒绝将新的设置为真

public class ToggleBox {

    private static boolean alreadyTrue = false;

    private static List<ToggleBox> listAll = new ArrayList<>();

    private boolean selected;

    public ToggleBox(boolean bool) {
        if (bool) {                    // if require true
            if (alreadyTrue)           // if there is already one
                bool = false;          // it will be false
            else                       // else
                alreadyTrue = true;    // it's st to true, and remember it
        }

        this.selected = bool;
    }

    @Override
    public String toString() {  return selected + "";  }

    public static void main(String argv[]) {
        ToggleBox m1 = new ToggleBox(true);
        ToggleBox m2 = new ToggleBox(false);
        System.out.println(Arrays.toString(listAll.toArray()));  // [true, false]
        ToggleBox m3 = new ToggleBox(true);
        System.out.println(Arrays.toString(listAll.toArray()));  // [true, false, false]
    }

}