hi,
any body explain to me overriding hashcode and equals methods
in collections especially.
import java.util.HashSet;
import java.util.Set;
public class Employee {
int empid;
String empname;
static Employee e1, e2;
Employee(int id, String name) {
empid = id;
empname = name;
}
public static void main(String[] args) {
e1 = new Employee(12, "lod");
e2 = new Employee(12, "lod");
boolean a;
Set hs = new HashSet();
a = hs.add(e1);
System.out.println(a);
a = hs.add(e2);
System.out.println(a);
System.out.println(hs);
}
@Override
public int hashCode() {
//System.out.println("Hi");
return empid;
}
public boolean equals(Object o) {
//System.out.println("hi1");
if (e1.empid == e2.empid) {
return true;
} else {
return false;
}
}
}
please any one explain this hashcode ovveriding and equals method internally how it will excute. and also which method executes first, here i used only 2 elements if i want for more than 3 elements how to write.
hashcode ovveridden means unique hashcodes are providing based on body implemention and improves retriving the elements.
here i written in hashcode body return empid means based on empid it will return hashcode for that object or some other else.
if writing instead of empid, 55 what is the meaning of this.and getting output same. and also what is the workflow behind these.
please let me know as soon as possible