| Author |
A question about "equals"
|
Vince Cheung
Greenhorn
Joined: Dec 06, 2004
Posts: 16
|
|
Why does the answer is "false"? How do I change it to "true"?
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9946
|
|
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 ]
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
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.
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9946
|
|
|
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
Joined: Feb 20, 2001
Posts: 580
|
|
|
Also, remember to override hashCode() when you override equals().
|
James Carman, President<br />Carman Consulting, Inc.
|
 |
Chengwei Lee
Ranch Hand
Joined: Apr 02, 2004
Posts: 884
|
|
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.
|
SCJP 1.4 * SCWCD 1.4 * SCBCD 1.3 * SCJA 1.0 * TOGAF 8
|
 |
 |
|
|
subject: A question about "equals"
|
|
|