d0ngd0ng said:
The solution of the problem is elegant,and it's a good idea.
I think it's possible to happen in real development requirement.
I hope not. I wouldn't let it past a commit-check where I work,
and would seriously scold the person who did it. "Naughty, nauthty,
naughty coder!".
The "solution" depends on an implementation specific choice made by
the writer of HashSet that is not reflected in the Set interface or
HashSet documentation (namely that it uses the equals method on the
parameter to compare, not the one on the object already in the
set). This could change in the next update of the JRE without breaking
anything but this fragile example of how *not* to code things.
And it uses side effects in a method traditionally expected not to
have any.
This is "Programming by conincidence" at its best. "See, it works,
so it must be good", without considering how easily it may break.
It's a hack to avoid rewriting the existing code to support the
operations needed. If you need a way to extract the member of the
equivalence class that is in the collection, given an equivalent value
that is not in it, you should use a different data structure that
supports, and reflects that it supports, that operation.
E.g., a Map with each entry having key and value equal.
You can work with its keyset if you need a set.
And it must be your own code we are talking about, where you have
created the HashSet, if you know it is a HashSet. Other people's code
should expose the collection as just a Set.
/L