gpt4 book ai didi

java - 使用对象的实例作为 HashMap 键

转载 作者:行者123 更新时间:2023-11-30 06:51:13 24 4
gpt4 key购买 nike

我发现了类似的问题,但到目前为止,没有一个问题真正对我有帮助(这可能意味着我做错了什么,这就是我在这里的原因)。

我有一个 HashMap Map<Integer, List<Book>>应该有 StudentID作为键和 Book 的列表他拥有作为值(value)的东西。虽然只通过了ID由于关键有效,我觉得它不是一种足够面向对象的方法,我应该使用 Student作为键(所以它看起来像这样: Map<Student, List<Book>> )。我尝试使用它,但是当我尝试返回给定的 Student 时,出现了一堆错误。的列表Book ,很可能是因为 Student没有找到。我的教授建议我@Override Java 的 hashCodeequals方法,这是有道理的,因为这就是HashMap比较键,但我在这方面还没有成功(我不确定我到底需要比较什么才能查看两个 Student 是否相同;据说,它们的 ID 单独应该起作用)。以下是重写的方法:

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
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 (id != other.id)
return false;
return true;
}

我做错了什么?您对此的任何说明都会非常有帮助。提前致谢!

最佳答案

错误似乎出现在您的 equals 方法中,前提是您的 id 的值超出了整数缓存范围,即 -128 - 127

 if (id != other.id) // <-- Error
return false;

从你的例子来看,id似乎是一个Integer对象

== checks whether the references are equal, i.e. whether they point to the same object.

For primitive types, == checks whether the values are equal.

java.lang.Integer is a reference type. int is a primitive type.

Although in case of Integer, == only works for numbers between -128 and 127 as JVM caches those values

您需要将其更改为

if (!id.equals(other.id))
return false;

关于java - 使用对象的实例作为 HashMap 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42736351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com