HashSet存储相等的对象 [英] HashSet storing equal objects

查看:131
本文介绍了HashSet存储相等的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是从对象列表中查找重复对象的代码。但由于某种原因,hashset甚至存储了相同的对象。

Below is the code for finding duplicate objects from a list of object. But for some reason the hashset is storing even the equal objects.

我肯定错过了这里的东西但是当我检查hashset的大小时它出来了5。

I am certainly missing out something here but when I check the size of hashset it comes out 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();
}
}


推荐答案

这代码不能满足您的需要:

This code doesn't do what you need it to:

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

这不是重写Object.equals,这是HashSet使用的。你需要:

That's not overriding Object.equals, which is what HashSet uses. You need:

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

请注意,使用 @Override 注释,你要求编译器验证你实际上覆盖了一个方法。

Note that by using the @Override annotation, you're asking the compiler to verify that you're actually overriding a method.

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

As noted, you also need to override hashCode in a way which is compatible with your equals method. Given that you're checking equality based on size, the simplest option would be:

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

这篇关于HashSet存储相等的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆