• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals method

 
manimiit kandan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can any body tell me,how the equals method comparing,this is my program

class equ{

String title;
int age;
equ(String title,int age){
this.title=title;
this.age=age;
}
public static void main(String[] a){
equ e=new equ("one",12);
equ e1=new equ("one",12);
System.out.println(e.equals(e1));
String s=new String("hello");
String s1=new String("hello");
System.out.println(s.equals(s1));
}
}

The first output statement display false,the second one true.
I don't know which way it's comparing
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please be aware to post the right questions in the right forum so that they get answered.
 
Adi Kulkarni
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi manimiit,

In your case, e is pointing to an object in the heap and e1 is pointing to a new and different object in the heap.Hence, the equals method is returing a false. Both the references should point the same object if you want the result to be true.

Second case is that of Strings. s.equals(s1) compares the sequence of characters and returns true if found true.

Kindly refer javadocs for more information.

Thanks,
Aditya
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The default equals method in the object class just does a reference comparison. So it returns false. You have to override it with your own implementation to get the desired results. Also override the hashcode method.
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In simple terms, String class has an equals implementation and your class equ does not have and instead uses the default one form the Object class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic