HashSet Saves Same Objects

Below is the code for finding duplicate objects from the list of objects. But for some reason, hashset even stores equal objects.

Of course, I am missing something here, but when I check the hashset size, it exits 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(); } } 
+4
source share
1 answer

This code does not do what you need to:

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

This is not an override of Object.equals that uses a HashSet. 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 using the @Override annotation @Override you ask the compiler to verify that you are actually overriding the method.

EDIT: As already noted, you also need to override hashCode in a way that is compatible with your equals method. Given that you are checking for equality in size, the simplest option would be:

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

All Articles