I have this class:private static class ClassA{int id;String name;public ClassA(int id, String name){ this.id= id; this.name = name;}@Overridepublic boolean equals(Object o) { return ((ClassA)o).name.equals(this.name);}}Why this main is printing 2 elements if I am overwriting the method equals in ClassA to compare only the name?public static void main(String[] args){ ClassA myObject = new ClassA(1, "testing 1 2 3"); ClassA myObject2 = new ClassA(2, "testing 1 2 3"); Set<ClassA> set = new HashSet<ClassA>(); set.add(myObject); set.add(myObject2); System.out.println(set.size()); //will print 2, but I want to be 1!}If I look into the Set Java documentation:A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.So apparently I only have to override equals, however I heard that I have also to override the hashcode, but why? 解决方案 They have different hashes because you didn't override hashCode. This means they were put in two different buckets in the HashSet, so they never got compared with equals in the first place.I would addpublic int hashCode() { return name.hashCode();}Notice id isn't used in the hashCode because it isn't used in equals either.(P.S. I'd also like to point out the irony of having an id that isn't used in equals. That's just funny. Usually it's the other way around: the id is the only thing in equals!) 这篇关于用Set实现等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 11:35