I have written the below program and not able to understand the output.
package com.demo.strings;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
class Emp
{
private int empNo;
private String empName;
public Emp(int empno, String empname)
{
this.empNo=empno;
this.empName=empname;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public boolean equals(Object obj)
{
if(obj != null && obj instanceof Emp)
{
String name = ((Emp)obj).getEmpName();
if(name.equals(this.getEmpName()))
{
return true;
}
}
return false;
}
public int hashcode()
{
return (this.hashCode()+1);
}
}
public class StringDemo {
public static void main(String[] args) {
Emp e1 = new Emp(1,"Stack");
Emp e2 = new Emp(1,"Stack");
Map<Integer,Emp> empMap = new HashMap<Integer,Emp>();
empMap.put(1,e1);
empMap.put(2,e2);
System.out.println(empMap.size());
System.out.println("Both objects are equal: "+e1.equals(e2));
}
}
output:2 Both objects are equal: true
I've overridden equals
and hashcode
, so Map
is supposed to store only one object in it. But it appears to be storing both of them. Is the way equals
and hashcode
were overridden wrong? Can anyone explain me how to fix this?