Dear friends, Why these following two examples are giving different results? Example1.java public class Example1 { public static void main(String[] args) { Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.println(n1.equals(n2)); } } result is true.
Example2.java class Value { int i; } public class Example2{ public static void main(String[] args) { Value v1 = new Value(); Value v2 = new Value(); v1.i = v2.i = 100; System.out.println(v1.equals(v2)); } } result is false.
i enclose the definition as given in the API for the equals method of Object. "The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true)." since the two references are to two different objects this returns false. U r thus not comparing the variables i in the objects but the objects themselves. Hope this helps
[This message has been edited by rahul_mkar (edited May 04, 2000).]
Yes Rahul is right. The Integer class overrides the .equals method that it inherits from the Object to provide content-based comparison. However, the Value class that you have defined does not override the equals method, and so it is actually calling the Object.equals() method. Hope this helps Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Don't listen to Steve. Just read this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss