當試圖創建一個標誌枚舉讓它包含多個狀態時。我注意到一些奇怪的東西。更改枚舉的內部值時,它的名稱不會更改。奇怪的是,這種內在價值(在我的情況下,一個int)保持的最高值,直到我明確的值設置爲0爲什麼在枚舉設置爲null後,此值得到保留
這是我用過進一步測試該
public enum flags {
None(0), flag1(1 << 0);
private int value;
private flags(int value) {
this.value = value;
}
public boolean hasFlag(flags flag) {
return (flag.value & value) == flag.value;
}
public void addFlag(flags flag) {
value |= flag.value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
枚舉
我嘗試了這些東西來設置枚舉值0
flags flag = flags.None;
System.out.println(flag + " " + flag.getValue());
// prints: None 0
flag.addFlag(flags.flag1);
System.out.println(flag + " " + flag.getValue());
// prints: None 1
flag = flags.None;
System.out.println(flag + " " + flag.getValue());
// prints: None 1 even though
// its been set to flags.None which has a value of 0
flag = null;
flag = flags.None;
System.out.println(flag + " " + flag.getValue());
// prints: None 1. Even though the enum has been set to null before
// setting the value to null
flag = null;
flag = flags.flag1;
flag = flags.None;
System.out.println(flag + " " + flag.getValue());
// prints: None 1. Even though it is set to
// another value after being set to null
// and then set to None
flag.setValue(0);
System.out.println(flag + " " + flag.getValue());
// prints: None 0. As expected
我的問題是:爲什麼 如此執着的價值,這裏發生了什麼?
您正在修改兩個對象的狀態。你爲什麼驚訝自己的狀態被修改了? –
enum上的setter應該是一個紅旗(雙關語意思)。 – Robert
作爲一個說明,最好遵循約定,並使用駱駝案例爲你的枚舉/類名等 – Orestis