在Java枚举中使用==可以吗?


问题内容

是否可以==在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;
    }


}