gpt4 book ai didi

java - 为什么我无法从哈希表中正确检索?

转载 作者:行者123 更新时间:2023-12-02 04:52:17 26 4
gpt4 key购买 nike

为什么我无法从哈希表中正确检索?我创建了一个哈希表,其中包含键和值,它们都是坐标类型(我创建的类)。然后我无法从坐标对象中检索 x 值。

public coordinates translateOffsetToPixel(int x, int y){
//Translate given coordinates to pixel coordinates for the cell
coordinates input = new coordinates(x,y);
coordinates outputPixelCoord;

Hashtable <coordinates, coordinates> table = new Hashtable<coordinates, coordinates>();

for (int r = 0 ; r<row; r++){
for(int c = 0; c< col; c++){
System.out.println("hit translation");
table.put(new coordinates(r,c), new coordinates(r*2,c*2));
}
}

outputPixelCoord = table.get(input);
System.out.println("outputX:" + outputPixelCoord.getX()); //ERROR
return outputPixelCoord;

}

坐标类:

public class coordinates {
private int x,y;
public coordinates(int x, int y){
this.x = x;
this.y = y;
}

public int getX() {return x;}

public int getY() {return y;}

}

可记录:

03-17 13:55:53.690    1961-1961/com.example.sam.matrix D/ViewRootImpl﹕ ViewPostImeInputStage ACTION_DOWN
03-17 13:55:53.780 1961-1961/com.example.sam.matrix I/System.out﹕ hit board
03-17 13:55:53.780 1961-1961/com.example.sam.matrix I/System.out﹕ 5
03-17 13:55:53.780 1961-1961/com.example.sam.matrix I/System.out﹕ hit translation
03-17 13:55:53.780 1961-1961/com.example.sam.matrix E/InputEventReceiver﹕ Exception dispatching input event.
03-17 13:55:53.780 1961-1961/com.example.sam.matrix E/MessageQueue-JNI﹕ Exception in MessageQueue callback: handleReceiveCallback
03-17 13:55:53.800 1961-1961/com.example.sam.matrix E/MessageQueue-JNI﹕ java.lang.NullPointerException

最佳答案

对于 Hashtable (和 HashMap)要正确存储和检索 key , key 类型必须正确覆盖 hashCodeequals

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

您尚未重写这些方法,因此 Hashtable 无法找到您的 key 。重写这些方法。

关于java - 为什么我无法从哈希表中正确检索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29106605/

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