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