hashCode中的对象等价

时间:2013-11-15 20:30:03

标签: java equals

我第一次使用hashCode并且不确定如何检查两个对象是否相等。这是我到目前为止所做的。

/** Represents a City */
class City {
/** Decimal format to print leading zeros in zip code */
static DecimalFormat zipFormat = new DecimalFormat("00000");

    int zip;
    String name;
    String state;
    double longitude;
    double latitude;


    /** The full constructor */
    public City (int zip, String name, String state, 
            double longitude, double latitude) {
            this.zip   = zip;
            this.name  = name;
            this.state = state;
            this.longitude = longitude;
            this.latitude  = latitude;
}

/** to make sure the two cities have the same name, state, zip code,
    * and the same latitude and longitude */
    public boolean equals(Object obj){
        if (obj == null)
            return false;
            City temp = (City)obj;

            System.out.println(City.equals(obj));
    }

2 个答案:

答案 0 :(得分:0)

假设您的情况中的相等意味着您的equals方法中的所有属性都相同

City temp = (City)obj;
return this.zip == temp.zip &&
       this.name == temp.name &&
       ...
;   

答案 1 :(得分:-1)

eclipse为您自动生成:

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        long temp;
        temp = Double.doubleToLongBits(latitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(longitude);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((state == null) ? 0 : state.hashCode());
        result = prime * result + zip;
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        City other = (City) obj;
        if (Double.doubleToLongBits(latitude) != Double
                .doubleToLongBits(other.latitude))
            return false;
        if (Double.doubleToLongBits(longitude) != Double
                .doubleToLongBits(other.longitude))
            return false;
        if (name == null)
        {
            if (other.name != null)
                return false;
        }
        else if (!name.equals(other.name))
            return false;
        if (state == null)
        {
            if (other.state != null)
                return false;
        }
        else if (!state.equals(other.state))
            return false;
        if (zip != other.zip)
            return false;
        return true;
    }