Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Java enum members: == or equals()?

Tags:

java

enums

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?

like image 514
Matt Ball Avatar asked Nov 17 '09 17:11

Matt Ball


People also ask

Can we call == to compare enums?

There are two ways for making comparison of enum members :equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can you use == on enum Java?

Yes, == is fine - there's guaranteed to be just a single reference for each value. An even better way of doing it is to put the functionality within the enum itself, so you could just call roundingMode.

Does enum complement comparable?

Enum implements Comparable interface and it's compareTo() method compares only same type of enum. Also natural order of enum is the order in which they are declared in code.


1 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.

like image 94
Reverend Gonzo Avatar answered Oct 05 '22 04:10

Reverend Gonzo