• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() method

 
Ming
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I found this question in the book of A Programmer's Guide to Java Certification by Khalid A.Mughal.
If the references x and y denote two different objects, then the expression x.equals(y) is always false.
True of false? I think it is true, but the answer of the book is false. Can anybody explain this?
I appreciate it.
 
Junilu Lacar
Bartender
Pie
Posts: 7274
44
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is false because the result of x.equals(y) depends on how x implements the equals() method. With only the information that x and y are different objects, you still cannot say for sure that x.equals(y) is always false.
Peter Haggar has a very good discussion about implementing the equals() method in his book "Practical Java".

[This message has been edited by JUNILU LACAR (edited June 11, 2001).]
 
Marcellus Tryk
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The equals() method is meant to test the equivalence of two objects. What equivalence means is up to the implementation of the class. You define equivalence for your class by overriding the equals(Object obj) method inherited from Object.
This is illustrated in the following example. a and b are two different Integer objects but they are considered 'equal'.

Output:

[This message has been edited by Tod Tryk (edited June 11, 2001).]
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this?


[This message has been edited by Thomas Paul (edited June 12, 2001).]
 
Marcellus Tryk
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmmm.....
That's interesting - but should work.
- T
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic