1

How can i remove objects having the same state.

          class Student{
                private int age;
                private String name;

                Student(int age, String name){
                  this.age=age;
                  this.name=name;
               } }

              public class SetTest {
               public static void main(String[] args) {
            Student s1= new Student(15,"abc");
            Student s2= new Student(15,"abc");
            Student s3= new Student(16,"adfc");
            Student s4= new Student(14,"ayuc");

                Set<Student> ss= new HashSet<Student>();
                ss.add(s1); ss.add(s2); ss.add(s3); ss.add(s4);}}

here s1 and s2 are having equal state and as i am using Set and I want to keep only one instance. What should i do to take only object with non-equal instance.

shekhar
  • 95
  • 1
  • 3

2 Answers2

3

You need to override the equals() and hashCode() methods in the Student class. In this method you define what it means for 2 students to be equal.

   @Override
   public boolean equals(Object other){
       //code to determine if this student is equal to other

   }

    @Override
    public int hashCode() {
       //code to generate a hashCode for the student
    }

Pay attention to the advice in this question.

Community
  • 1
  • 1
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
1

You need to override the equals() and hashCode() methods in your Student class.

class Student {
    ...
    @Override
    public boolean equals(Object obj) {
        // Your own logic
        // return super.equals(obj); // default
    }

    @Override
    public int hashCode() {
        // Your own logic
        // return super.hashCode(); // default
    }
}
Rahul
  • 44,383
  • 11
  • 84
  • 103