Java HashSet is allowing dupes; problem with compa

2019-04-21 08:32发布

I've got a class, "Accumulator", that implements the Comparable compareTo method, and I'm trying to put these objects into a HashSet.

When I add() to the HashSet, I don't see any activity in my compareTo method in the debugger, regardless of where I set my breakpoints. Additionally, when I'm done with the add()s, I see several duplicates within the Set.

What am I screwing up, here; why is it not Comparing, and therefore, allowing the dupes?

Thanks,
IVR Avenger

8条回答
啃猪蹄的小仙女
2楼-- · 2019-04-21 09:21

You need to correctly implement hashCode() and equals().

You must override hashCode and return a number based on the values in your class such that any two equal objects have the same hashcode.

查看更多
Juvenile、少年°
3楼-- · 2019-04-21 09:22

When ever you create an object of class Accumulator it takes new space in JVM and returns unique hashCode every time you add an object in hashSet. It does not depends upon the value of the object because you have not overridden hashCode() method hence it will call Object class hashCode() method which will return unique hashCode with every object created in your program.

Solution:

Override hashCode() and equals() method and apply your logic depending upon the properties of your class. Be sure to read equals and hashcode contract

http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html

查看更多
登录 后发表回答