gpt4 book ai didi

Java - HashMap不能使用新对象作为搜索键

转载 作者:行者123 更新时间:2023-11-30 02:18:14 25 4
gpt4 key购买 nike

我在这里想做的是使用键Key用对象Obj填充HashMap,当我完成时我想要可以根据任何可能的键访问这些值。我编写了以下代码,发生的情况是,虽然第一个显示确实显示了我想要的值,但第二个显示引发了 NullPointerException

import java.util.*;

public class My{
public static void main(String[] args){
Map<Key,Obj> myMap = new HashMap<Key,Obj>();

Obj ob1 = new Obj("Nick",19);
Obj ob2 = new Obj("George",17);

Key key1 = new Key(1,2);
Key key2 = new Key(2,1);

myMap.put(key1,ob1);
myMap.put(key2,ob2);

myMap.get(key1).show();
myMap.get(new Key(1,2)).show();

}

我可以看出,Java 无法告诉 new Key(1,2)key1 相等,但我不知道如何克服这个问题。

public class Obj{

private String name;
private int age;

Obj(String name, int age){
this.name = name;
this.age = age;
}

public void show(){
System.out.println(name + " " + age);
}
}

这些是我使用的类

import java.* ;

public class Key{

public int x,y;

Key(int x, int y){
this.x = x;
this.y = y;
}

public boolean equals(Key d){
if ((this.x == d.x)&&(this.y == d.y)){
return true;
}
else{
return false;
}
}
}

最佳答案

您在实现 Key 时遇到两个问题。首先,equals'方法签名是错误的 - 它应该是public boolean equals(Object)。如果您使用了 @Override 注释,此错误很容易被注意到。其次,您还应该重写 hashCode() 方法:

@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
Key key = (Key) o;
return x == key.x && y == key.y;
}

@Override
public int hashCode() {
return Objects.hash(x, y);
}

关于Java - HashMap不能使用新对象作为搜索键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641697/

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