java - HashSet 存储相等的对象

标签 java equals hashset duplicate-removal

下面是从对象列表中查找重复对象的代码。但出于某种原因,哈希集甚至存储了相同的对象。

我肯定在这里遗漏了一些东西,但是当我检查哈希集的大小时,结果是 5。

import java.util.ArrayList;
import java.util.HashSet;


public class DuplicateTest {

public static void main(String args[]){
    ArrayList<Dog> dogList = new ArrayList<Dog>();
    ArrayList<Dog> duplicatesList = new ArrayList<Dog>();
    HashSet<Dog> uniqueSet = new HashSet<Dog>();

    Dog a = new Dog();
    Dog b = new Dog();
    Dog c = new Dog();
    Dog d = new Dog();
    Dog e = new Dog();

    a.setSize("a");
    b.setSize("b");
    c.setSize("c");
    d.setSize("a");
    e.setSize("a");

    dogList.add(a);
    dogList.add(b);
    dogList.add(c);
    dogList.add(d);
    dogList.add(e);

    if(a.equals(d)){
        System.out.println("two dogs are equal");
    }
    else System.out.println("dogs not eqal");

    for(Dog dog : dogList){
        uniqueSet.add(dog);
    }

    System.out.println("number of unique dogs="+ uniqueSet.size());
    /*for(Dog dog:uniqueSet){
        System.out.println("uniqueset ="+dog.getSize());
    }

    for(Dog dog : duplicatesList){
        System.out.println("duplicate dog="+dog.getSize());
    }*/

}

}

这是 Dog 类

public class Dog implements Animal, Comparable<Dog>{

String size;

public void makeNoise(){
    System.out.println("woof woof");
}

public String getSize() {
    return size;
}

public void setSize(String size) {
    this.size = size;
}

public int compareTo(Dog d){
    return this.size.compareTo(d.size);
}

public boolean equals(Dog d){
    return this.size.equals(d.size);
}

@Override
public int hashCode() {
    // TODO Auto-generated method stub
    return super.hashCode();
}
}

最佳答案

此代码没有执行您需要的操作:

public boolean equals(Dog d){
    return this.size.equals(d.size);
}

这并没有覆盖 HashSet 使用的 Object.equals。你需要:

@Override
public boolean equals(Object d){ 
    if (!(d instanceof Dog)) {
        return false;
    }
    Dog dog = (Dog) d;
    return this.size.equals(dog.size);
}

请注意,通过使用 @Override 注释,您要求编译器验证您实际上正在覆盖一个方法。

编辑:如前所述,您需要以与您的equals 方法兼容的方式覆盖hashCode。鉴于您要根据大小检查相等性,最简单的选择是:

@Override
public int hashCode() {
    return size.hashCode();
}

关于java - HashSet 存储相等的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722485/

相关文章:

java - 嵌套 try catch

java - org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity

java - 为 BST 实现 equals 和 hashcode

algorithm - 是否有可能在恒定时间内找到 Set 中的随机元素?

java - 检索使用 ScheduledExecutorService 计划的任务实例

java - 在 JTextPane 中查找字符串的偏移量

java - 自定义对象作为映射键

c# - 带有自定义类键的慢字典

algorithm - 在 O(n) 相交中排序

memory - 字典使用 Trie 还是 SortedSet?