首页 > 解决方案 > 对于我编写的以下代码,我应该如何覆盖 java 中的 hashCode 和 equals 方法

问题描述

我有一个关于汽车登记的项目。我有一个名为 RegNo 的类,它实现了类似的接口。当我在 hashmap 中使用它时,它应该包含被覆盖的 equals 和 hashCode 函数。请帮助我解决这个问题。类代码如下:

package main;

public class RegNo implements Comparable<RegNo> {
    private final String regNo;
    
    public RegNo(String regNo)
    {
        this.regNo = regNo;
    }
    
        
    /*
     * implementing the compareTO method which is defined
     *  in Comparable class as an abstract method
     *  the method returns 0 if both the registration numbers being compared are equal
     *  it returns 1 if the regNo of the object calling this method is lexicographically greater than the parameter
     *  and the method returns a -1, if the regNo of the parameter is greater than the object calling the method
     *  */
    @Override
    public int compareTo(RegNo reg) {
        // TODO Auto-generated method stub
        if(this.regNo == reg.regNo) //both the registration numbers are equal
            return 0;
        else if(this.regNo.compareTo(reg.regNo) > 0)
            return 1;
        else
            return -1;
    }
}

标签: javahashmap

解决方案


尝试委托字符串的方法

        public static class RegNo implements Comparable<RegNo> {
            private final String regNo;

            public RegNo(String regNo)
            {
                this.regNo = regNo;
            }

            @Override
            public int compareTo(RegNo reg) {
                return regNo.compareTo(reg.regNo);
            }

            @Override
            public boolean equals(Object o) {
                if (o == null || getClass() != o.getClass()) return false;

                if (this == o) return true;

                RegNo regNo1 = (RegNo) o;
                return regNo.equals(regNo1.regNo);
            }

            @Override
            public int hashCode() {
                return regNo.hashCode();
            }
        }

推荐阅读