Two Laptop Bag
The moose likes Beginning Java and the fly likes A question about Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A question about "equals"" Watch "A question about "equals"" New topic

A question about "equals"

Vince Cheung

Joined: Dec 06, 2004
Posts: 16
Why does the answer is "false"? How do I change it to "true"?
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11884

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 ]

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
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

Joined: Oct 02, 2003
Posts: 11884

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.


SCJP 1.4 * SCWCD 1.4 * SCBCD 1.3 * SCJA 1.0 * TOGAF 8
I agree. Here's the link:
subject: A question about "equals"
It's not a secret anymore!