| Author |
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
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9191
|
|
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: 36
|
|
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
|
|
|
http://www.javapractices.com/topic/TopicAction.do?Id=28
|
 |
 |
|
|
subject: Collections question.
|
|
|