对于我编写的以下代码,我应该如何重写java中的hashCode和equals方法

对于我编写的以下代码,我应该如何重写java中的hashCode和equals方法,java,hashmap,Java,Hashmap,我有一个关于汽车登记的项目。我有一个名为RegNo的类,它实现了可比较的接口。它应该包含被覆盖的equals和hashCode函数,因为我正在hashmap中使用它。请帮我处理这件事。课程代码如下: package main; public class RegNo implements Comparable<RegNo> { private final String regNo; public RegNo(String regNo) {

我有一个关于汽车登记的项目。我有一个名为RegNo的类,它实现了可比较的接口。它应该包含被覆盖的equals和hashCode函数,因为我正在hashmap中使用它。请帮我处理这件事。课程代码如下:

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;
    }
}
packagemain;
公共类RegNo实现了可比较的{
私有最终字符串regNo;
公共注册号(字符串注册号)
{
this.regNo=regNo;
}
/*
*实现定义的compareTO方法
*作为一种抽象方法在可比类中
*如果要比较的两个注册号相等,则该方法返回0
*如果调用此方法的对象的regNo在字典上大于参数,则返回1
*如果参数的regNo大于调用该方法的对象,则该方法返回-1
*  */
@凌驾
公共int比较(注册号reg){
//TODO自动生成的方法存根
if(this.regNo==reg.regNo)//两个注册号相等
返回0;
如果(此注册表项与(注册表项)>0,则为else)
返回1;
其他的
返回-1;
}
}

尝试委托字符串的方法

        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();
            }
        }
公共静态类RegNo实现可比较{
私有最终字符串regNo;
公共注册号(字符串注册号)
{
this.regNo=regNo;
}
@凌驾
公共int比较(注册号reg){
返回regNo.compareTo(reg.regNo);
}
@凌驾
公共布尔等于(对象o){
如果(o==null | | getClass()!=o.getClass())返回false;
如果(this==o)返回true;
RegNo regNo1=(RegNo)o;
返回regNo.equals(regNo1.regNo);
}
@凌驾
公共int hashCode(){
返回regNo.hashCode();
}
}

这个问题有用吗?您的
compareTo()
方法应该使用equals()或compareTo()来比较这两个字符串。==只用于测试两个字符串是否指向同一个对象。@ Farzana——如果需要用CultEngult:NULL//CULL调用CuffReto,则需要考虑一下。