Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Modify id that changes hashcode

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.

like image 890
Andrii Andriichuk Avatar asked Jul 17 '12 20:07

Andrii Andriichuk


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

The documentation of Object says: "maintain the general contract for the hashCode() method, which states that equal objects must have equal hash codes"

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:

  1. Remove the object, change it and add it again - works wonderful, easiest way if a HashSet is mandatory

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

like image 175
Anytoe Avatar answered Sep 30 '22 15:09

Anytoe