将对象映射为关键字

how*_*rdh 2 java map

我想创建一个具有某个类作为键的映射.我遇到的问题是,由于这个类包含指针,如果我使用HashMap,则在散列时使用此地址(请参阅下面的代码).我怎样才能比较实际值而不是地址,或者我可以使用其他容器来实现相同的结果吗?

import java.util.*;
public class Main {
    public static void main(String args[]) {
        class Foo {
            public Foo(String a) {s = a;}
            public String s;
        }

        HashMap<Foo,Integer> a = new HashMap<Foo,Integer>();
        a.put(new Foo("test"), 1);
        System.out.println(a.get(new Foo("test")));
    }
}
Run Code Online (Sandbox Code Playgroud)

这输出 null

das*_*ght 9

为了使用类的实例作为键,HashMap您需要覆盖它hashCodeequals方法.一旦你这样做,一切都应该工作正常.

class Foo {
    public Foo(String a) {s = a;}
    public String s;
    int hashCode() {return s.hashCode();}
    boolean equals(Object other) {
        if (other == this) return true;
        if (!(other instanceof Foo)) return false;
        return ((Foo)other).s.equals(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @howardh`hashCode`不需要是唯一的(事实上它大部分时间都不是唯一的),但它必须遵守[hashcode/equals contract](http://docs.oracle.com/javase/1.4) Java的.2/docs/api/java/lang/Object.html#hashCode()) - 每次在同一个对象上调用它时都必须相同,并且对于相同的对象必须相同,但不能必然相反(即具有相同哈希码的对象不必相等). (3认同)