I have recently run into an issue using HashSet.addAll(Object) where duplicates are added to my Set.
I even made sure that the Object I was using Overrode hashCode().
Apparently the addAll() implementation for HashSet doesn't check for duplicates. This is bad because a reason for using a Set over a List is to avoid duplicate values.
If you loop through all of the values in the collection you are adding to the Set it works as expected not adding the duplicates. This is the approach I took to get around this issue.
for (item in myCollection){
set.add(item)
}
vs what I was trying to do which didn't work:
set.addAll(myCollection)
Another approach could be extend the HashSet and override the addAll() with the logic I used.
No comments:
Post a Comment