在下面,我希望值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)));
}
答案 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;
}
我相信添加这两种方法后,您的代码将可以正常工作。