Java学习笔记--HashMap中使用object做key的问题【转】

在HashMap中,如果需要使用多个属性组合作为key,可以将这几个属性组合成一个对象作为key。但是存在的问题是,要做get时,往往没办法保存当初put操作时的key object的reference,此时,需要让key object覆盖如下hashCode()和equals(Object obj)的实现。sample code如下:

public class TestKeyObject {
    private long id;
    private int type;

    public TestKeyObject(long id, int type) {
        this.id = id;
        this.type = type;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    //定义HashCode的计算方式
    public int hashCode() {
        int ret = new Long(id).hashCode() ^ new Integer(type).hashCode();
        // 也可以用下面这种方式计算hashCode
        // int ret = String.valueOf(id).hashCode() ^
        // String.valueOf(type).hashCode();
        System.out.println(ret);
        return ret;
    }

    //定义相等的条件
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }
        if (!(obj instanceof TestKeyObject)) {
            return false;
        }
        TestKeyObject tmpObj = (TestKeyObject) obj;
        return tmpObj.id == id && tmpObj.type == type;
    }

}
原文地址:https://www.cnblogs.com/gnivor/p/4782915.html