是否可以在 Java 中的枚举上使用 ==
,还是需要使用 .equals()
?在我的测试中, ==
总是有效,但我不确定我是否能保证这一点。特别是,枚举上没有 .clone()
方法,所以我不知道是否有可能获得 .equals()
的枚举返回与 ==
不同的值。
例如,这样可以吗:
public int round(RoundingMode roundingMode) {
if(roundingMode == RoundingMode.HALF_UP) {
//do something
} else if (roundingMode == RoundingMode.HALF_EVEN) {
//do something
}
//etc
}
还是需要这样写:
public int round(RoundingMode roundingMode) {
if(roundingMode.equals(RoundingMode.HALF_UP)) {
//do something
} else if (roundingMode.equals(RoundingMode.HALF_EVEN)) {
//do something
}
//etc
}
最佳答案
只要我的 2 美分:这是 Sun 发布的 Enum.java 的代码,也是 JDK 的一部分:
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, 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;
}
}
关于java - 可以在 Java 中的枚举上使用 == 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/533922/