Java Overriding equals and hashCode with Generics [duplicate]

允我心安 提交于 2019-12-26 15:06:06

问题


In a java class i have the following code:

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;
    }
}

I use an HashMap and i want to use keys with the Couple type. For example if i want to insert a new element in the HashMap i do the following:

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

How should i Override the equals and hashCode methods in the Couple class using Generics?


回答1:


Sample equals() implementation for Couple could be like:

@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));
}

And hashcode() example:

@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;
}


来源:https://stackoverflow.com/questions/24681416/java-overriding-equals-and-hashcode-with-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!