Is it OK to use ==
on enums in Java, or do I need to use .equals()
? In my testing, ==
always works, but I'm not sure if I'm guaranteed of that. In particular, there is no .clone()
method on an enum, so I don't know if it is possible to get an enum for which .equals()
would return a different value than ==
.
For example, is this OK:
public int round(RoundingMode roundingMode) {
if(roundingMode == RoundingMode.HALF_UP) {
//do something
} else if (roundingMode == RoundingMode.HALF_EVEN) {
//do something
}
//etc
}
Or do I need to write it this way:
public int round(RoundingMode roundingMode) {
if(roundingMode.equals(RoundingMode.HALF_UP)) {
//do something
} else if (roundingMode.equals(RoundingMode.HALF_EVEN)) {
//do something
}
//etc
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…