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

标签 java hash logic hashtable

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

相关文章:

Java - 是否可以实例化用户定义类或java基本类型

c++ - C++ std::hash 实现总是确定性的吗?

ios - 在六边形 map 上显示最大范围

c# - 在 C# 中创建 URL 简码

ruby - ruby 中的组合逻辑问题

c# - 同时检查多个 boolean 返回值

java - flatMap() 将 LinkedList<String> 流转换为 String 流

java - 在jodaTime中获取主格月份名称

java - 如何区分触摸板点击

AJAX 登录调用中的 Javascript 散列,更安全?