Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet storing equal objects

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.

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());
    }*/

}

}

And here is the Dog class

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();
}
}
like image 805
antnewbee Avatar asked Feb 17 '23 23:02

antnewbee


1 Answers

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

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

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);
}

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

EDIT: 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();
}
like image 141
Jon Skeet Avatar answered Mar 01 '23 12:03

Jon Skeet