java - Element is present but `Set.contains(element)` returns false -


how can element not contained in original set in unmodified copy?

the original set not contain element while copy does. see image.

the following method returns true, although should return false. implementation of c , clusters in both cases hashset.

public static boolean confumbled(set<string> c, set<set<string>> clusters) {     return (!clusters.contains(c) && new hashset<>(clusters).contains(c)); } 

debugging has shown element is contained in original, set.contains(element) returns false reason. see image.

could please explain me what's going on?

if change element in set (in case elements set<string>, adding or removing string change them), set.contains(element) may fail locate it, since hashcode of element different when element first added hashset.

when create new hashset containing elements of original one, elements added based on current hashcode, set.contains(element) return true new hashset.

you should avoid putting mutable instances in hashset (or using them keys in hashmap), , if can't avoid it, make sure remove element before mutate , re-add afterwards. otherwise hashset broken.

an example :

set<string> set = new hashset<string>(); set.add("one"); set.add("two"); set<set<string>> setofsets = new hashset<set<string>>(); setofsets.add(set); boolean found = setofsets.contains(set); // returns true set.add("three"); set<set<string>> newsetofsets = new hashset<set<string>>(setofsets); found = setofsets.contains(set); // returns false found = newsetofsets.contains(set); // returns true 

Comments