• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections question.

 
Alex Serna
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Valentin Ivanov
Ranch Hand
Posts: 38
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic