为什么我不能从我的哈希表中正确检索?

Why can't I properly retrieve from my hashtable?

为什么我不能从我的哈希表中正确检索?我创建了一个由键和值组成的哈希表,它们都是 Coordinate 类型(我创建的 class)。然后我无法从我的坐标对象中检索 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;

}

坐标Class:

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)正确存储和检索密钥,密钥类型必须正确覆盖 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 无法找到您的密钥。覆盖那些方法。

您需要像这样覆盖 hashCode 和 equals 方法,以便可以从 HashTable/HashMap 等中存储和检索它。

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;}

    public int hashCode() {
        // This is just a random way to generate hash
        // see other ways to generate hash before you implement this
        return x + (37 * y)
    }

    public boolean equals(Object obj) {
        if (obj instance of Coordinates) {
            Coordinates c = (Coordinates)obj;
            return c.x == this.x && c.y == this.y;
        }
        return false;
    }
}