本文介绍了Java重写equals和hashCode与泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

   示例equals()实现 Couple 可能类似于:

  @Override 
public boolean equals(Object obj){
if(!(obj instanceof Couple))
return假;
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());
返回结果;
}


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?

解决方案

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

这篇关于Java重写equals和hashCode与泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:07