How to override equals and hashCode method in java
Demo Program:
package com.techiedeveloper.set;
import java.util.HashSet;
public class Student {
private int marks;
private String name;
public Student(int marks, String name) {
super();
this.marks = marks;
this.name = name;
}
public static void main(String[] args) {
Student s1 = new Student(10, "abc");
Student s2 =new Student(10, "abc");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.equals(s2));
System.out.println("s1 hashcode"+s1.hashCode());
System.out.println("s2 hashcode"+s2.hashCode());
HashSet Student hs = new HashSet();
hs.add(s1);
hs.add(s2);
System.out.println(hs);
}
@Override
public boolean equals(Object obj) {
Student sobj = (Student)obj;
return sobj.name.equals(this.name) && sobj.marks==this.marks;
}
@Override
public int hashCode() {
return this.marks*this.name.hashCode();
};
}