zoukankan      html  css  js  c++  java
  • 【思考】为什么JAVA要同时重写equals和hashcode

    什么是equals

    equals()在java.lang.Object下

    其源码为: 所以Object对象的equals其实就是比较是否为同一对象的引用

    public boolean equals(Object obj) {
            return (this == obj);
    }

    举例:

    Student s1=new Student(001,"王大锤");
    Student s2=new Student(001,"王大锤");
    //结果为false
    System.out.println(s1.equals(s2));

    equals()在String下

    只比较值,因为在String类中对equals方法进行了重写的原因。

    String str1="123";
    String str2="123";
    //print true
    System.out.println(str1.equals(str2));

    什么是hashcode方法

    在java中,对对象的存储采取了存储在哈希表中处理方法,hashcode方法是根据对象的地址转换之后返回的一个哈希值

    就需要对哈希表有一个基本的认识。其基本的结构如下:

    对于hashcode方法,会返回一个哈希值,哈希值对数组的长度取余后会确定一个存储的下标位置,如图中用数组括起来的第一列。

    不同的哈希值取余之后的结果可能是相同的,时候就用equals方法判断是否为相同的对象,不同则在链表中插入。

    所以:

    hashcode不相同,用equals()方法判断的返回的一定为false。

    hashcode相同,equals()方法返回值不能确认,可能为true,可能为false。

    先调用hashCode,唯一则存储,不唯一则再调用equals,结果相同则不再存储,结果不同则散列到其他位置。因为hashCode效率更高(仅为一个int值),比较起来更快。

    样例说明:

    1.只重写了equals

     测试类:

    结果:

    出现矛盾!!!

    用equals比较说明对象相同,但是在HashMap中却以不同的对象存储(没有重写hascode值,两个hascode值,在他看来就是两个对象)。到底这两个对象相等不相等????说明必须重写hashCode()的重要性,

    2.同时重写equals方法和hashCode方法

     测试类

     结果

  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/linhongwenBlog/p/12783683.html
Copyright © 2011-2022 走看看