java - 可以在 Java 中的枚举上使用 == 吗?

标签 java syntax enums

是否可以在 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/

相关文章:

java - 将 0 和 1 的字符串转换为字节

java - JPanel GridLayout 不添加组件

java - 我需要单击名为“使用 java 中的 selenium webdriver 注册新闻通讯”的复选框

header 函数中的 PHP 变量

mysql - 需要将此表与子字符串相加才能找到正确的值

scala - 如何从 Scala 访问 Java 枚举?

php - php中的通用枚举类型

java - GridBagLayout 未正确排列按钮

text - NANO 中一行 "Comment"的键盘快捷键?

c# - 获取 Enum<T> 值 描述