4

I made an own class called Region and I store instances of Region in a HashSet. I use a HashSet, that there are no Objects which are equal in the list. The String name of a Region should be unique in the HashSet, so I have overriden the equals method.

My Question:

What happens if I store two regions with different names into the HashSet and then I make the different names equal (by a setter for the name)?

This is no duplicate. The other question is about equal HashSets and not about equal objects in HashSets.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
stonar96
  • 1,359
  • 2
  • 11
  • 39
  • 1
    What happened when you tried it? – Sotirios Delimanolis Sep 03 '14 at 19:44
  • 3
    Undefined behaviour. Don't do that. Read the first "note" here: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html – Oliver Charlesworth Sep 03 '14 at 19:45
  • 1
    "_What happens if ..._" You know you could just do it and see right? – takendarkk Sep 03 '14 at 19:46
  • Related: http://stackoverflow.com/questions/16402970/changing-the-elements-in-a-set-changes-the-equals-semantics – clcto Sep 03 '14 at 19:47
  • 1
    @Takendarkk I don't think this is the kind of thing one can just "try and see". Probably if he changes the name, nothing will happen right away, but some future operation *may* now fail, but won't necessarily, and the OP wouldn't know which future operation to try. Most "what happens if" questions could be addressed the way you did, **but not all**. – ajb Sep 03 '14 at 19:53
  • Your question is not entirely clear. If you're talking about changing the data that is used by equals/hashvalue *while* the object is in the set, then that's a no-no. Anything that is done to the object to change it's hash value or response to *equals* while in the set breaks the "contract", and "undocumented behavior" is likely. – Hot Licks Sep 03 '14 at 21:25
  • My Question is solved for me. I made the String name of the Region class final and removed the setter, so there is no option to change the name. I didn't know that there is no method for a String that changes the String itself, so a final String can never be changed. right? – stonar96 Sep 04 '14 at 20:00
  • `String` in Java is a **completely immutable** object. You can not change it in any way. Each method will instead create a new object with updated content. So yes, making the string `final` should be safe, the string can not be changed nor re-assigned anymore. – Zabuzard Jan 24 '18 at 04:12

1 Answers1

5

The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.

-- the Set Javadoc

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413