• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

equals method

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?.
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rajeev Nair
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since there is no equals() method defined by MyClass, the one from Object is used. The equals() method in Object effectively does a == comparison as explained by Will.
 
WiLL Tao
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some class override the equals method, so it compare the vale,eg:String class
JAVA DOC
Overrides:
equals in class Object

The interesting is that StringBuffer does not override equals meothd.
Please look this code

Hope it helps.
 
Rajeev Nair
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Will and Arun, I got it now
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!