equals is not your friend

posted Jun 21, 2011, 8:17 PM by Marsh Gosnell   [ updated Jun 22, 2011, 5:29 AM ]

I fixed a bug in a Java application recently that took me a while to find because the code looked OK but was fatally flawed.  The statement that caused all the grief was:

          If (shelfType.equals(m_neType)) { 

If the statement was written as:

          If (shelfType == m_neType) {

there would have been a nasty compiler error stating you cannot compare a ShelfType object to an NE object.  Using equals trumped that compatibility test and the equals() always returned false for many months. 

The moral of this story is that equals() is not your friend and should never be used to compare objects when == and != can be used.  Only use equals() when the native comparison operators cannot be used (e.g., comparing the contents of objects like a String).

Comments