aspose file tools
The moose likes Beginning Java and the fly likes When to override the equals method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "When to override the equals method" Watch "When to override the equals method" New topic
Author

When to override the equals method

Doshi Milan
Ranch Hand

Joined: May 29, 2001
Posts: 112
Dear friends,
I wanred to know when should one override the equals() method.If you override the equals() method, should you do anything else.
Thanks in advance,
Reagrds,
Milan
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Actually every class should override the equals and hashcode methods. This insures that objects of that class will be properly stored in hash and set objects.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
I wouldn't say "every class" -- not every class has a meaningful notion of semantic equality between different instances.
But if you do override equals(), you MUST override hashCode(), and adhere to the contract: equal objects have equal hash codes (but unequal objects don't necessarily have unequal hash codes)
[ October 12, 2002: Message edited by: Ron Newman ]

Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
You may want to take a look at The October Newsletter.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: When to override the equals method
 
Similar Threads
Overriding hashCode()
A question about hashCode
equals( ) explanation ?
Doubt Regarding HashSet
collections- MAP USE