【问题标题】:Issues with using HashTable in Java在 Java 中使用 HashTable 的问题
【发布时间】:2012-03-27 22:36:17
【问题描述】:

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

节点类:

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。知道为什么吗?

【问题讨论】:

    标签: java map hashmap hashtable


    【解决方案1】:

    您需要在 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 方法才能正确运行。您应该实现一个反映对象逻辑的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() 方法。

    【讨论】:

    • 所以,方法应该是这样的:布尔等于(节点节点1,节点节点2),对吧?
    • 知道了:public boolean equals(Object obj) { return (this == obj); }
    • 没有。它需要在 Node 类中并且具有确切的签名 boolean equals(Object)
    • 没有public boolean equals(Object o)。您可以将o 转换为Node 对象并将其与this 进行比较。 this == obj 不会帮助你,因为它是默认的 Object.equals 实现导致你的麻烦。在my blog post 上无耻地做广告。您可以使用右侧菜单“Traduzir”组合框翻译文章。
    • @Perception:这不是“你可能还想实现一个hashCode() 方法”;它是“您必须还实现hashCode() 方法”。如果您覆盖equals 而不是hashCode,那么它们将不一致,您最终会遇到来自HashMap 的未定义行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2016-03-28
    • 2010-10-24
    • 2013-10-30
    • 1970-01-01
    • 2018-03-10
    • 2010-10-02
    相关资源
    最近更新 更多