H
Harald Kirsch
Roughly I do something along the lines of:
Set set = new HashSet();
Set elem = new HashSet();
set.add(elem);
// now we change the elem and add it again to the set
elem.add(some object here);
set.add(elem);
I found out the hard way that 'set' may now contain
'elem' either once or twice, the reason being that
'elem.add()' changes the hashCode of elem such that
it is not noticed that it is in 'set' already on the
2nd 'set.add()'.
Question: What I would actually want is an
IdentityHashSet() set = new IdentityHashSet()
but this does not seem to exist (what a shame). Any
idea how to get the required effect with minimal coding?
Would it be worth to define the element type myself as
a subclass of HashSet, overriding the hashCode() with
System.identityHashCode()?
Comments?
Harald.
Remark: I am obviously using HashSet in the wrong way, but
on the other hand, the behaviour is a bit dubios. Alas I
would not know how to improve the HashSet implementation
without forcing an equals() on every element during .add().
Set set = new HashSet();
Set elem = new HashSet();
set.add(elem);
// now we change the elem and add it again to the set
elem.add(some object here);
set.add(elem);
I found out the hard way that 'set' may now contain
'elem' either once or twice, the reason being that
'elem.add()' changes the hashCode of elem such that
it is not noticed that it is in 'set' already on the
2nd 'set.add()'.
Question: What I would actually want is an
IdentityHashSet() set = new IdentityHashSet()
but this does not seem to exist (what a shame). Any
idea how to get the required effect with minimal coding?
Would it be worth to define the element type myself as
a subclass of HashSet, overriding the hashCode() with
System.identityHashCode()?
Comments?
Harald.
Remark: I am obviously using HashSet in the wrong way, but
on the other hand, the behaviour is a bit dubios. Alas I
would not know how to improve the HashSet implementation
without forcing an equals() on every element during .add().