首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对于我编写的以下代码,我应该如何重写java中的hashCode和equals方法

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

Stack Overflow用户
提问于 2021-04-16 09:59:49
回答 1查看 22关注 0票数 0

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

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-16 11:01:16

尝试委托字符串的方法

代码语言:javascript
复制
        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();
            }
        }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67118134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档