• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about "equals"

 
Vince Cheung
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the answer is "false"? How do I change it to "true"?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you need to override the equals method your class A inherits from Object.

By default, the inherited method compares (i think) the memory address of the two objects. since you have two distinct objects, they have a different memory space, so they are not equal.

in your class A, create an equals method that does what you want, like


[ March 10, 2005: Message edited by: fred rosenberger ]
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To override Object.equals(Object) in accordance with its contract, you need to do a little more.



Note that passing equals(Object) an argument that is null or is a different type is legal and returns false. This is different from compareTo(Object), which throws a ClassCastException if the argument is not the same type and a NullPointerException if the argument is null.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry my answer was incomplete. i was trying to get something helpful up quickly, and... well... i just plead being tired.
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, remember to override hashCode() when you override equals().
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vince,

The equals method in your class needs to be implemented in order for it to make sense. By default, it doesn't contains any implementation, since you could have so many different kinds of objects & to test for equality, many require different criterias.

Hence, it is up to the developer to implement their own equals method if they wish to use it.

To make sense & see how to do it, read the Effective Java by Joshua Bloch. Sun had provided a few sample chapters & one of them shows to how to override a few important methods such as equals, hashCode, toString & clone.

Or if you just want to get things done, try using Jakarta Commons Lang.

HTH.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic