当我们将User对象作为键时,如何从HashMap获得价值,如下所示

时间:2018-11-13 09:17:33

标签: java hashmap

在下面,我希望值400需要通过传递其键来打印。我可以知道怎么做吗?

  public static void main(String[] args) {
    HashMap<Student, Integer> hmap=new HashMap<Student, Integer>();

    hmap.put(new Student(101, "Srinu", 5000), 100);
    hmap.put(new Student(102, "Srinu", 5000), 200);
    hmap.put(new Student(103, "Srinu", 5000), 300);
    hmap.put(new Student(104, "Srinu", 5000), 400);

    System.out.println(hmap.get(new Student(104, "Srinu", 5000)));
    System.out.println(hmap.containsKey(new Student(104, "Srinu", 5000)));

  }

2 个答案:

答案 0 :(得分:4)

您需要覆盖hashCode()类的equals()Student方法。让您的IDE自动生成这两个。

答案 1 :(得分:1)

在Student.java文件中添加这两种方法:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + no;
    result = prime * result + num;
    return result;
}


@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Student other = (Student) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (no != other.no)
        return false;
    if (num != other.num)
        return false;
    return true;
}

我相信添加这两种方法后,您的代码将可以正常工作。