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 always used .equals()
, eg
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?
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.
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 clone
method in Enum
ensures that enum
constants 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 an enum
type exist beyond those defined by the enum
constants.
Because there is only one instance of each enum
constant, it is permissible to use the ==
operator in place of the equals
method when comparing two object references if it is known that at least one of them refers to an enum
constant . (The equals
method in Enum
is a final
method that merely invokes super.equals
on 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)
What are the differences between ==
and equals
?
As a reminder, it needs to be said that generally, ==
is NOT a viable alternative to equals
. When it is, however (such as with enum
), there are two important differences to consider:
==
never throws NullPointerException
enum Color { BLACK, WHITE };
Color nothing = null;
if (nothing == Color.BLACK); // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException
==
is subject to type compatibility check at compile time
enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };
if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT); // DOESN'T COMPILE!!! Incompatible types!
Should ==
be used when applicable?
Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that ==
is usable. enum
is specifically mentioned to exemplify.
Item 1: Consider static factory methods instead of constructors
[...] it allows an immutable class to make the guarantee that no two equal instances exist: a.equals(b)
if and only if a==b
. If a class makes this guarantee, then its clients can use the ==
operator instead of the equals(Object)
method, which may result in improved performance. Enum types provide this guarantee.
To summarize, the arguments for using ==
on enum
are:
Using ==
to compare two enum values works because there is only one object for each enum constant.
On a side note, there is actually no need to use ==
to write null safe code if you write your equals()
like this:
public useEnums(SomeEnum a)
{
if(SomeEnum.SOME_ENUM_VALUE.equals(a))
{
...
}
...
}
This is a best practice known as Compare Constants From The Left that you definitely should follow.
链接地址: http://www.djcxy.com/p/2674.html上一篇: “同步”是什么意思?