equals method

public class Q19 { public static void main(String[] args) { MyClass a = new MyClass(100); MyClass b = new MyClass(100); if(a.equals(b)) System.out.println("Objects have the same values"); else System.out.println("Objects have different values"); } } class MyClass { static int maxElements; MyClass(int maxElements) { this.maxElements = maxElements; // System.out.println("value:" +this.maxElements); the value is 100 for both a and b } } The value for both a and b is 100 . When equals method gets executed it prints "Objects have different values". Why?.

Now the equals method is only SHALLOW compare. It only compare the hasocode of object(usually memory address). MyClass a and MyClass b both use new keyword for creating, they have different hashcode,so "Objects have different values" will be printed in the end. Hope it helps. [ April 21, 2002: Message edited by: WiLL Tao ]

Thank Folks who <b>Make Sense</b> here.<br />SCJP Platform 2

Rajeev Nair
Ranch Hand

Joined: Mar 11, 2002
Posts: 51

posted Apr 21, 2002 21:37:00

0

Thanks Will, But my understanding was equals method compares the value whereas == compares the memory address. if i replace equals with (a==b), it prints "Objects have different values"