Re: hashcode calculation for a Collection of objects
kaldrenon wrote:
On Aug 8, 7:58 pm, Patricia Shanahan <p...@acm.org> wrote:
Alternatively, create a new HashSet containing the
elements of the List and test it for equality to the set.
Couldn't this easily break due to sets containing no duplicate?
Consider List X == ["A","A","B"] and Set Y == ["A","B"]. If you
convert X to a set it will become ["A","B"], will it not?
Unless the conditions of the algorithm guarantee uniqueness in both
Collections, converting a List to a Set sounds dangerous and could
lead to error.
Remember the problem description this was intended to solve: "If you
really want to know if the list and set contain exactly the
same items..."
Your X and Y do contain exactly the same items, so the comparison should
return true.
Conversion of List to Set is an information-destroying operation, but in
this particular case, the information that gets destroyed is exactly the
superfluous information that prevents compareTo from getting the right
answer. Sometimes, it is good to destroy information.
I would agree with you if the problem were to determine if the list and
set contain the same items the same number of times each.
Patricia