This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • 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: 9509
22
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic