equals method - how to override

后端 未结 3 620
别那么骄傲
别那么骄傲 2020-12-22 12:35

I need help on to override the equals method. I have everything working except for the equals method. The equals method that I current

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 13:16

    Your equals() method has some errors like:

    if(this == dollars && this == cents)
    

    This will never be true... this must be:

    if(this.dollars == dollars && this.cents == cents)
    

    But I won't put any effort in coding the equals, is recommended to autogenerate equals. Something like this:

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Currency other = (Currency) obj;
        if (cents != other.cents)
            return false;
        if (dollars != other.dollars)
            return false;
        return true;
    }
    

    Also is highly recommended, (nearly unavoidable as @AdriaanKoster commented) when you override equals() method, also override hashCode()
    In equals() definition:

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

    Hash code:

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + cents;
        result = prime * result + dollars;
        return result;
    }
    

提交回复
热议问题