在Java中的枚举上使用==可以吗? [英] Is it OK to use == on enums in Java?

查看:574
本文介绍了在Java中的枚举上使用==可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在Java中的枚举上使用 == ,还是需要使用 .equals()?在我的测试中, == 总是有效,但我不知道我是否得到保证。特别地,在枚举上没有 .clone()方法,所以我不知道是否可以获得一个枚举,其中 .equals()将返回与 == 不同的值。



例如,这是OK:

  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
}
/ pre>

解决方案

只需我的2美分:这是Sun发布的Enum.java的代码, JDK:

  public abstract class Enum< E extends Enum< E> 
实现Comparable< E>可序列化{

// [...]

/ **
*如果指定的对象为等于这个
*枚举常数。
*
* @param其他要与此对象相等的对象进行比较。
* @如果指定的对象等于此
*枚举常量,则返回true。
* /
public final boolean equals(Object other){
return this == other;
}


}


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<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中的枚举上使用==可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆