0

I just want to remove duplicate elements from list. To do this I have written a POJO class Student as :

class Student{

private String roll;
private String name;

public Student(String roll, String name) {
    this.roll = roll;
    this.name = name;
}
@Override
public boolean equals(Object obj) {
    Student st = (Student) obj;
    return st.getRoll().equals(roll);
}

public String getRoll() {
    return roll;
}
public void setRoll(String roll) {
    this.roll = roll;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Override
public String toString() {
    return roll ;
}

}

And a test class as below :

public class TestMain {
public static void main(String[] args) {

    List<Student> list = Arrays.asList(
            new Student("19", "goutam kumar singh"),
            new Student("20", "goutam kumar singh"),
            new Student("11", "goutam kumar singh"),
            new Student("19", "goutam kumar singh")
            );

    List<Student> arrayList = new CopyOnWriteArrayList<>(list);
    Set<Student> set = new HashSet<>();

    for(Student st : arrayList)
        set.add(st);
    System.out.println(set);
}
}

but in the output all the four elements in the set but i am expecting only three element as fourth element is duplicate and must be removed.

Where I am going wrong?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • Why are you overriding the `equals()` method...? – Wyatt Lowery Nov 09 '15 at 12:46
  • http://stackoverflow.com/questions/2707541/why-should-i-override-hashcode-when-i-override-equals-method – Natix Nov 09 '15 at 12:47
  • 6
    See [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – takendarkk Nov 09 '15 at 12:48

2 Answers2

7

You have to override the hashCode() method too. Override hashCode() methods for those property for which you override equals() method.

While working with Collection it's useful to remember the contract between hashCode() and equals() method -

1. If two objects are equal, then they must have the same hash code.
2. If two objects have the same hashcode, they may or may not be equal.

For more information you may visit this link

Razib
  • 10,965
  • 11
  • 53
  • 80
2

A HashSet stores elements internally as keys in a HashMap. Because of this, it will use your Student object as the keys for that map, using the hash code for each object. Since you don't provide an implementation for this method hashCode(), the default one from Object is used and each of your students will have a different hash code.

You must extend this method in your class, being aware of the equals-hashCode contract. If two objects are equal, they must have the same hashCode (the reverse isn't allways true). For further details see this Object.hashCode()

Slimu
  • 2,301
  • 1
  • 22
  • 28