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?
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.