温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

equals和hashcode是什么

发布时间:2020-11-10 10:37:11 来源:亿速云 阅读:156 作者:小新 栏目:编程语言

小编给大家分享一下equals和hashcode是什么,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

equals和hashcode总结:

equals方法没有重写的话,用于判断对象的内存地址引用是否是用一个地址。重写之后一般用来比较对象的内容是否相等(比如student对象,里面有姓名和年龄,我们重写equals方法来判断只要姓名和年龄相同就认为是用一个学生)。

hashCode是jdk根据对象的地址或者字符串或者数字算出来的int类型的数值,当然你也可以重写它,hashcode方法只有在集合中用到。

对象放入集合中时,先判断hashcode是否相等,再判断equals是否相等,都相等就算是同一个对象,list则可以放入,set因为不允许重复所以不会放入。

例如:

public class Student {
        private int age;
        private String name; 
        public Student(int age ,String name){
            this.age = age;
            this.name = name;
        }
        public int getAge() {
           return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
           return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        //重写equals方法,判断姓名和年龄相同就是相等的
        public boolean equals(Object o){
            if(o == null){
                return false;
            }
            if(this.getClass() != o.getClass()){
             return false;   
            }
            Student student = (Student)o;
            if(name == null){
                return false;
            }
            if(age==student.getAge()&&name.equals(student.getName())){
                return true;
            }
            return false;
        }       
    public static void main(String[] args) {
        Student studentOne = new Student(1,"yjc");
        Student studentTwo = new Student(1,new String("yjc"));
        System.out.println(studentOne.equals(studentTwo));
        System.out.println("1: "+studentOne.getName().hashCode());
        System.out.println("2: "+studentTwo.getName().hashCode());
    }
    //输出结果:true
                1: 119666
                2: 119666
}

以上可以看出,两个String都叫"yjc",无论是直接"yjc"还是new String("yjc"),他们的hashcode都相同。所以在重写hashcode方法时可以运用这一点。

比如你希望如果姓名和年龄相同,不仅equals相同,他们的hashcode也要相同,可以这样重写hashcode:

public int hashcode(){
    final int prime = 31; 
    int result = 1;    
    result = prime*result + age;    
    result = prime*result + (name == null? 0 : name.hashcode());   
    return result;//直接写age+(name == null? 0 : name.hashcode())也行就是感觉太简单了0.0
}

这样一来两个姓名和年龄相同的Student对象就是同一个对象了,放入set中会被认为是同一个,无论放几个这样的对象,set.size()都是等于1。

同样,HashMap因为key也是唯一的,HashMap对象是根据其Key的hashCode来定位存储位置,并使用equals(key)获取对应的Value,所以在put时判断key是否重复用到了hashcode和equals,若重复了则会覆盖。

看完了这篇文章,相信你对equals和hashcode是什么有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI