Comparing Java Enum Members: == or Equals()?
I Know That Java Enums Are Compiled to Classes with Private Constructors and a Bunch of Public Static Members. When Comparing Two Members of a Given Enum, I've...
I know that Java enums are compiled to classes with private constructors and a bunch of public static members. When comparing two members of a given enum, I've always used .equals(), e.g.
public useEnums(SomeEnum a)
{
if(a.equals(SomeEnum.SOME_ENUM_VALUE))
{
...
}
...
}
However, I just came across some code that uses the equals operator == instead of .equals():
public useEnums2(SomeEnum a)
{
if(a == SomeEnum.SOME_ENUM_VALUE)
{
...
}
...
}
Which operator is the one I should be using?
15 Answers
Both are technically correct. If you look at the source code for .equals(), it simply defers to ==.
I use ==, however, as that will be null safe.
Must Read
Can == be used on enum?
Yes: enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification (emphasis by me):
JLS 8.9 Enums
An enum type has no instances other than those defined by its enum constants.
It is a compile-time error to attempt to explicitly instantiate an enum type. The
final clonemethod inEnumensures thatenumconstants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of anenumtype exist beyond those defined by theenumconstants.Because there is only one instance of each
enumconstant, it is permissible to use the==operator in place of theequalsmethod when comparing two object references if it is known that at least one of them refers to anenumconstant. (Theequalsmethod inEnumis afinalmethod that merely invokessuper.equalson its argument and returns the result, thus performing an identity comparison.)
This guarantee is strong enough that Josh Bloch recommends, that if you insist on using the singleton pattern, the best way to implement it is to use a single-element enum (see: Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type; also Thread safety in Singleton)