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

时间:2015-03-17 18:07:20

标签: java hash logic hashtable

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

}

LOGTABLE:

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

2 个答案:

答案 0 :(得分:1)

要使Hashtable(和HashMap)正确存储和检索密钥,密钥类型必须正确覆盖hashCodeequals

  

要成功存储和检索哈希表中的对象,用作键的对象必须实现hashCode方法和equals方法。

您尚未覆盖这些方法,因此Hashtable无法找到您的密钥。覆盖这些方法。

答案 1 :(得分:1)

您需要覆盖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;
    }
}