Java覆盖equals和hashCode with Generics

时间:2014-07-10 16:09:55

标签: java generics hashmap

在java类中,我有以下代码:

private class Couple<V extends Comparable<V>>{

    private V v1;
    private V v2;

    public Couple(V v1, V v2){
        this.v1 = v1;
        this.v2 = v2;
    }
}

我使用HashMap,我想使用Couple类型的键。例如,如果我想在HashMap中插入一个新元素,我会执行以下操作:

HashMap<Couple<V>, Integer> map = new HashMap<Couple<V>, Integer>();
map.put(new Couple<V>(v1, v2), new Integer(10));

我应该如何使用Generics覆盖Couple类中的equals和hashCode方法?

1 个答案:

答案 0 :(得分:3)

Couple的示例equals()实现可能如下:

@Override
public boolean equals(Object obj) {
   if (!(obj instanceof Couple))
        return false;
    if (obj == this)
        return true;

    Couple couple = (Couple) obj;    
    return (this.v1 != null && this.v1.equals(couple.v1) 
            && this.v2 != null && this.v2.equals(couple.v2));
}

和hashcode()示例:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((v1 == null) ? 0 : v1.hashCode());
    result = prime * result + ((v2 == null) ? 0 : v2.hashCode());
    return result;
}