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
}
解决方案
Just my 2 cents: Here is the code for Enum.java, as published by Sun, and part of the JDK:
public abstract class Enum>
implements Comparable, Serializable {
// [...]
/**
* Returns true if the specified object is equal to this
* enum constant.
*
* @param other the object to be compared for equality with this object.
* @return true if the specified object is equal to this
* enum constant.
*/
public final boolean equals(Object other) {
return this==other;
}
}