• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
Sheriffs:
  • Devaka Cooray
  • paul wheaton
  • Mark Herschberg
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
  • Jj Roberts
Bartenders:
  • Carey Brown
  • salvin francis
  • Piet Souris

HashMap and HashSet

 
Ranch Hand
Posts: 238
1
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I just read that two different objects can also have the same hashcode.
I have two question(assuming i have overridden hashCode( and equals())
1.Do we save objects of a particular class only in a given collection,or a collection can store any object of any class,
2.If a collection can store any object from any class,and i am using a HashMap for storing the objects,then what if i get the same hashcode values for the two objects?Then how will i save them?

Thanks...
 
Ranch Hand
Posts: 32
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The agreement is that objects which are equal have to provide the same hash code. Objects that have the same hash code, however, do not have to be equal.

You can store objects which have the same hash code in a HashSet or HashMap just fine. If they are equal, the second instance added will replace the first one. If the objects are not equal, you'll get what's called a hash collision. The map or set implementation will then take care of handling the second object appropriately, for instance by associating every used hashcode with a linked list holding all the non-equal objects with this hashcode.

You can run the following example yourself. Note that i have overridden hashCode in both Example classes to return a constant, something you obviously never want to do in the real world.

 
You would be much easier to understand if you took that bucket off of your head. And that goes for the tiny ad too!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic