问题
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