简体   繁体   中英

Custom objects not found in HashMap?

Hi i'm trying to learn the purpose of hashcode () and equals() method.I tried the following program.

import java.util.HashMap;

public class LearnHascode {

public String name;
public int age;
LearnHascode(String na)
{
    name = na;
}
public int hashCode()
{
    return name.hashCode();
}
public boolean equals(LearnHascode obj)
{
    return this.name.equals(obj.name);
}
public static void main(String[] args)
{
    HashMap h = new HashMap();
    LearnHascode ob1 = new LearnHascode("Prabha");
    LearnHascode ob2 = new LearnHascode("Prabha");

    h.put(ob1, v1);
    h.put(ob2, v2);


    System.out.println(h);
    System.(h.out.printlncontainsKey(new LearnHascode("Prabha")));

}

}

output :

{hash.LearnHascode@8ef7bdfc=Two, hash.LearnHascode@8ef7bdfc=one}
false

I have two doubts :

1) I thought HashMap will contain one entry as hascode of the two objects (ob1 and ob2) are same. could any one explain why there are two entries in the HashMap?

2) why System.(h.out.printlncontainsKey(new LearnHascode("Prabha"))); returns false?

Your equals() method is wrong, and this breaks the HashMap . The argument to equals() is always an Object ; you have to check what kind of Object it is and cast it in the body of the method.

The hashCode() value is used to sort the objects into categories, but equals() is used to decide whether two objects are actually the same. You need to define both of these methods correctly to get HashMap to work.

you did not give proper implementaiton of hashCode() and equals() methods.

public class Employee {

private int empId;

private String empName;

public Employee(int id, String name){
    empId = id;
    empName = name;
}

public int getEmpId() {
    return empId;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

public String getEmpName() {
    return empName;
}

public void setEmpName(String empName) {
    this.empName = empName;
}


public int hashCode(){
    System.out.println("In Hash Code");
    int hashCode = 20;
    hashCode *= this.empId;
    hashCode += this.empName.hashCode();
    return hashCode;
}

public boolean equals(Object obj){
    System.out.println("In equals");
    if(!(obj instanceof Employee)){
        return false;
    }
    Employee emp = (Employee) obj;
    return (emp.getEmpName().equals(this.getEmpName())) && (emp.getEmpId() == this.getEmpId());
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM