File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections question. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections question." Watch "Collections question." New topic

Collections question.

Alex Serna
Ranch Hand

Joined: Sep 18, 2009
Posts: 58

Hi everyone,

I have read that in maps you need to override equals when you create your own class to use it as a key. I didn't do it and still it lets me insert elements as you can see in the following code:

I don't have much experience working with collections. I have read the collection's chapter in K & B book, but still I don't feel I confident with it. Does anyone know about a book or a website where collections are explained in more detail???

Ankit Garg

Joined: Aug 03, 2008
Posts: 9466

You were able to add elements to the Map but you won't be able to get elements out of it correctly. Look at this code

Although the ToDos object find that I created is meaningfully equivalent to t1, but I can't get the element out of the map using find as hashCode and equals were not overridden...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Valentin Ivanov
Ranch Hand

Joined: Nov 20, 2008
Posts: 38

hi Alex,

it is working that way because your class ToDos inherit equals() method from Object class. But in that way once you lose the reference(address) to the object, used as a key, you can't retreive that object because equals() method compares the bitpattern of the variables
Alex Serna
Ranch Hand

Joined: Sep 18, 2009
Posts: 58
Thank you very much, I understand it now. So the default equals from Obejct compares the references, but what about Object's hashcode, what's its behaviour?
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575
I agree. Here's the link:
subject: Collections question.
It's not a secret anymore!