Equals & Hashcode Concepts

package org;

import java.util.HashSet;
import java.util.Set;

public class TestClass {

public static void main(String args[]){

Emp emp1 = new Emp("Amit","Gupta"); 
Emp emp2 = new Emp("Gupta","Amit"); 
Set s = new HashSet();
s.add(emp1);
s.add(emp2);



System.out.println(emp1.hashCode());
System.out.println(emp2.hashCode());
System.out.println(emp2.equals(emp1));
System.out.println(s.size());

String fName="Amit" ;
String lName = "Gupta" ; 
int hashcode = fName.hashCode()+lName.hashCode();

System.out.println("Hahcode of class = "+emp1.hashCode());
System.out.println("Hahcode of f and l Name = "+hashcode);


}

}


package org;

import java.util.HashSet;
import java.util.Set;

public class Emp {
String fName ;
String lName;



Emp(String s, String p){
this.fName = s;
this.lName =p;

}


public String getfName() {
return fName;
}


public void setfName(String fName) {
this.fName = fName;
}


public String getlName() {
return lName;
}


public void setlName(String lName) {
this.lName = lName;
}

@Override
public boolean equals (Object o){

if(null==o){
return false; 
}else if(((Emp)o).getfName().equals(this.fName)&&
((Emp)o).getlName().equals(this.lName)){
return true;
}else
return false;
}

@Override
public int hashCode() {

return this.fName.hashCode()+this.lName.hashCode();




}

Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java