Saturday, May 22, 2010

Comparing Java Enums

Well it was seeming just another day in Office when a piece of checked in code caught my attention. It led to a constructive debate in the team and eventually we arrived at the conclusion as mentioned below.
I had used .equals() to compare two Enums as we all know that Object.equals() internally uses == operator two compare two references and for Enums which is true as two equal enums will always point to the same memory location as they are singleton in nature. I considered .equals() a comfortable and a standard way of comparing two Objects which could also be applied to Enums as well.
Here comes the different side of the story.The argument was Enums are basically constants and the convention is we should use == to compare constants. Since it didn't seem to be very convincing to me as object .equals() does the same thing and enum is not a primitive datatype like int etc, I decided to google on it.

It came out that using == over .equals() is more advantageous in two ways:

a) It gives you a compile time advantage. How? See below .















Comparing the EState enum with an ILamp using equals() is accepted perfectly by the compiler even though the condition never can be true in practice. Using == the compiler screams and tells us that we are comparing apples with oranges.

b)One can avoid the accidental and unwanted null pointer exceptions using == operator over .equals() making it null safe.

Though the second problem can be avoided, the first one seems to be a cool advantage during development

The interesting articles that i came across on this topic are below:
http://schneide.wordpress.com/2008/09/22/or-equals/
http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals