java - 在 Java 中使用 HashTable 的问题

标签 java dictionary hashmap hashtable

我正在尝试使用哈希表,当尝试搜索对象时,我看不到该对象,但如果打印它,我可以看到它。

节点类:

public class Node {

    int x;
    int y;


    public Node() {

        this.x=0;
        this.y=0;

    }

    public Node(int x,int y) {
        this.x=x;
        this.y=y;
    }



    public String toString(){

        return "(Node: x,y="+Integer.toString(x)+","+Integer.toString(y)+")";

    }

}

主类:

public class GridWalk {


    static Hashtable <Node, Integer> myMap;
    static Stack<Node> nodes;

    public static void main(String[] args) {

        myMap = new Hashtable<Node,Integer>();
        nodes=new Stack<Node>();

        Node start=new Node(0,0);

        Node new1= new Node(100,100);
        myMap.put(new1,new Integer(1));
        Node new2=new Node (100,100);
        System.out.println("Already there ? huh: "+new2.toString()+" at "+myMap.get(new2)); 

    }
}

当我执行打印行时,我得到 NULL。知道为什么吗?

最佳答案

您需要在 Node 类中重写并实现 equals 方法。 java.lang.Object 的默认实现仅比较引用的相等性,这不适合您的情况。

Node new1 = new Node(100, 100);
Node new2 = new Node(100, 100);

System.out.println(new1.equals(new2)); // Your current code will print false

HashMap 依赖于 equalshashCode 方法的正确实现才能正确运行。您应该实现一个反射(reflect)对象逻辑的equals 方法。像这样的东西:

public boolean equals(Object o) {
    if(this == o) return true;

    final Node other = (Node) o;
    return ((getX() == o.getX()) && (getY() == o.getY());
}

您可能还想在 Node 对象上实现 hashCode() 方法。

关于java - 在 Java 中使用 HashTable 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9651641/

相关文章:

java - 写但不读时java中的同步 HashMap

java - 键作为整数,值作为 IntegerArray

java - Mysql中的队列系统

Java 似乎没有正确比较 double

python - 循环中嵌套字典

python - 如何在 Python 3.3 中加密/解密字典?

java - Java 中键值对的有序集合

java - 跟踪类字节码中方法实现的变化

java - 读取和解析文本文件android

python - 如何避免两次写入 request.GET.get() 以打印它?