- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
每当我尝试运行该程序时,我都会得到以下输出:
6150
5000
1015612567
列表中的人员:
{A=100,B=50}
下一个:
人:A 哈希码:507806258 值:100
下一个:
人:B 哈希码:507806309 值:50
String name;
int day;
static Map<String, Integer> people = new HashMap<>();
public PeopleHash(String name, int day) {
this.name = name;
this.day = day;
}
public String getName() {
return name;
}
public int getDay() {
return day;
}
public boolean equals(PeopleHash other) {
if (other instanceof PeopleHash) {
PeopleHash d = (PeopleHash)other;
return name == d.name && day == d.day;
} else {
return false;
}
}
@Override
public int hashCode() {
return 50 * day;
}
public PeopleHash peopleEntry(){
String namn = "A";
int schiffre = 123;
return null;
}
public static void main(String[] args) {
PeopleHash p1 = new PeopleHash("Isolde", 123);
PeopleHash p2 = new PeopleHash("Jean", 100);
people.put("Person A", 100);
people.put("Person B", 50);
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
System.out.println("People in list: \n" + people);
for (Entry<String, Integer> entry : people.entrySet()) {
String a = entry.getKey();
int b = entry.getValue();
System.out.println("Next:");
System.out.println("Person: " + a + " Hashcode: " + entry.hashCode() + " Value: " + b);
}
}
}
我做错了什么?
最佳答案
哈希/等于本身没问题。问题在于使用(或缺乏)。
“Person:”输出显示 Map.Entry 的哈希码对象( entry.hashCode()
),并且与 p1/p2 没有关系。映射中的条目是通过字符串键添加的,并且 p1/p2 对象会被简单地丢弃。
map 可能应该声明为 Map<HashPerson, Integer>
这样将使用 HashPerson 的 equals/hashCode 。单个 person 对象应直接用作键:
people.add(p1, 1234);
那么循环可以写成这样:
for (Entry<HashPerson, Integer> entry : people.entrySet()) {
HashPerson person = entry.getKey();
Integer value = entry.getValue();
System.out.println(
String.format("Person %s HashCode: %d Value: %d",
person.getName(), person.hashCode(), value));
}
关于java - 我的哈希码不起作用 - 是我的 equals() 有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29261202/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!