Hashmap - Java Modify id that changes hashcode

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I use HashSet and I need to modify the ID of an object, but it changes hashcode and breaks HashSet and rules of hashCode() method.

What is best solution: to delete object from Set and add object with new ID, or to keep the hash code (generated in constructor, for example) in every object in Set, or is there other way to solve this problem?

Thanks for help.

UPDATE: I made mistake: keeping hash code in object is terrible, because in that case equal objects can have different hash codes.

Answers

A HashSet as a container accesses its items (contains, remove) via the hash code of the items you put into it. The hash code is often built by the state of its instance members. So the hash code changes with the manipulation of the state of the object.

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#equals%28java.lang.Object%29 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#equals%28java.lang.Object%29

As you noticed, if you change the state of an object you keep in a HashSet, the object can not longer be accessed by the remove method or found by the contains method of the HashMap.

The options you are offering are:

    • Remove the object, change it and add it again -
    works wonderful, easiest way if a HashSet is mandatory
    • Keep the value of the hash code somewhere - Means, you have the same hash code for objects which are not equal. Or if you obey the documentation you can encounter two objects which are equals and have the same hash code, but their member variables differ! This can lead to unpredictable errors.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/11530061/java-modify-id-that-changes-hashcode

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils