为什么我无法从哈希表中正确检索?我创建了一个哈希表,其中包含键和值,它们都是坐标类型(我创建的类)。然后我无法从坐标对象中检索 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 类型必须正确覆盖 hashCode
和 equals
。
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/