Home > DeveloperSection > Forums > Comparing Java enum members: == or equals()?
Samuel Fernandes
Samuel Fernandes

Total Post:156

Points:1096
Posted on    May-16-2015 12:26 AM

 Java Java 
Ratings:


 1 Reply(s)
 500  View(s)
Rate this:
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 come code that uses the equals operator == instead:

public useEnums2(SomeEnum a)
{
    if(a == SomeEnum.SOME_ENUM_VALUE)
    {
        ...
    }
    ...
}
I've been programming in Java for 5+ years, and I thought I understood difference between the two - but I'm still scratching my head at which one is more correct. Which operator is the one I should be using?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-16-2015 7:41 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick