Compare enums with == instead of equals() in Java
TIL you should compare enums with ==
instead of equals()
in Java.
a == SomeEnum.ENUM_VALUE
/* instead of */
a.equals(SomeEnum.ENUM_VALUE)
Last week I saw this pull request in a repository on GitHub. This PR triggered me to take a look at how I should compare enums in Java.
I used to compare enums with equals()
. In the API I saw that equals()
on an enum is the same as ==
, because this is what the equals()
implementation looks like:
public final boolean equals(Object other) {
return this==other;
}
I found two good points why you should use ==
instead of equals()
when comparing enums.
Prevent NullPointerExceptions
If you use ==
to compare an enum with NULL
, it will return false
. However, if you use equals()
to compare an enum with NULL
, you will probably get a NPE.
Type safety
The ==
operator checks if both enum objects are from the same enum type or not at compile time. This is in contrast to equals()
, which will return false
at runtime. I prefer—and I think you should too—to detect errors at compile time.