Sunday, July 13, 2008

Equality of Java Objects

There are 3 candidates for the equality test in Java:
1. Primitives
2. References
3. Objects


When we compare things in Java, what is really being compared? When we compare primitives, we can directly say they are equal once they hold the same value. Therefore they can be compared using the == operator. The same is true for reference variables, however, we are not comparing the actual values being referred to, rather we compare the pointers to the actual values.


Primitive



int someInt = 1;
if (someInt == 1) {
//this block will execute
}

The equality of two objects is tested using the equals method of the Object class. The default behavior of the equals method is just the same as the == operator. However, some classes override this method for a specific comparison. One example is the String class, the equals method is overridden to test the equality of the actual strings being held by two String objects.


Object without an overridden equals method



Object a = new Object();
Object b = new Object();

if (a.equals(b)) {
//this block will not execute
}

Object with an overridden equals method



String a = new String("I am a string!");
String b = new String("I am a string!");

if (a.equals(b)) {
//this block will execute depending on the implementation
//of the equals method, for this instance, it compares the string literals
//being held by two String objects
}

So if you are unsure of how the equals method behave in a specific class, RTF API documentation!

No comments: