【面经】被虐了之后,我翻烂了equals源码,总结如下

打印 上一主题 下一主题

主题 912|帖子 912|积分 2736


面试最常问的问题
1、equals比较的什么?
2、有没有重写过equals?
3、有没有重写过hashCode?
4、什么情况下需要重写equals()和hashCode()?
1) equals源码

目标:如果不做任何处理(可能绝大大大多数场景的对象都是这样的),jvm对同一个对象的判断逻辑是怎样的
我们先读一下Object里的源码:
  1.     /**
  2.      * Indicates whether some other object is "equal to" this one.
  3.      * <p>
  4.      * The {@code equals} method implements an equivalence relation
  5.      * on non-null object references:
  6.      * <ul>
  7.      * <li>It is <i>reflexive</i>: for any non-null reference value
  8.      *     {@code x}, {@code x.equals(x)} should return
  9.      *     {@code true}.
  10.      * <li>It is <i>symmetric</i>: for any non-null reference values
  11.      *     {@code x} and {@code y}, {@code x.equals(y)}
  12.      *     should return {@code true} if and only if
  13.      *     {@code y.equals(x)} returns {@code true}.
  14.      * <li>It is <i>transitive</i>: for any non-null reference values
  15.      *     {@code x}, {@code y}, and {@code z}, if
  16.      *     {@code x.equals(y)} returns {@code true} and
  17.      *     {@code y.equals(z)} returns {@code true}, then
  18.      *     {@code x.equals(z)} should return {@code true}.
  19.      * <li>It is <i>consistent</i>: for any non-null reference values
  20.      *     {@code x} and {@code y}, multiple invocations of
  21.      *     {@code x.equals(y)} consistently return {@code true}
  22.      *     or consistently return {@code false}, provided no
  23.      *     information used in {@code equals} comparisons on the
  24.      *     objects is modified.
  25.      * <li>For any non-null reference value {@code x},
  26.      *     {@code x.equals(null)} should return {@code false}.
  27.      * </ul>
  28.      * <p>
  29.      * 该方法用于识别两个对象之间的相似性
  30.      * 也就是说,对于一个非null值,x和y,当且仅当它们指向同一个对象时才会返回true
  31.      * 言外之意,和==没啥两样。
  32.      * The {@code equals} method for class {@code Object} implements
  33.      * the most discriminating possible equivalence relation on objects;
  34.      * that is, for any non-null reference values {@code x} and
  35.      * {@code y}, this method returns {@code true} if and only
  36.      * if {@code x} and {@code y} refer to the same object
  37.      * ({@code x == y} has the value {@code true}).
  38.      * <p>
  39.      * Note that it is generally necessary to override the {@code hashCode}
  40.      * method whenever this method is overridden, so as to maintain the
  41.      * general contract for the {@code hashCode} method, which states
  42.      * that equal objects must have equal hash codes.
  43.      *
  44.      * @param   obj   the reference object with which to compare.
  45.      * @return  {@code true} if this object is the same as the obj
  46.      *          argument; {@code false} otherwise.
  47.      * @see     #hashCode()
  48.      * @see     java.util.HashMap
  49.      */
  50.     public boolean equals(Object obj) {
  51.         return (this == obj);
  52.     }
复制代码
猜想:如果我们不做任何操作,equals将继承object的方法,那么它和==也没啥区别!
下面一起做个面试题,验证一下这个猜想:
  1. package com.eq;
  2. import java.io.InputStream;
  3. public class DefaultEq {
  4.     String name;
  5.     public DefaultEq(String name){
  6.         this.name = name;
  7.     }
  8.     public static void main(String[] args) {
  9.         DefaultEq eq1 = new DefaultEq("张三");
  10.         DefaultEq eq2 = new DefaultEq("张三");
  11.         DefaultEq eq3 = eq1;
  12.         //虽然俩对象外面看起来一样,eq和==都不行
  13.         //因为我们没有改写equals,它使用默认object的,也就是内存地址
  14.         System.out.println(eq1.equals(eq2));
  15.         System.out.println(eq1 == eq2);
  16.         System.out.println("----");
  17.         //1和3是同一个引用
  18.         System.out.println(eq1.equals(eq3));
  19.         System.out.println(eq1 == eq3);
  20.         System.out.println("===");
  21.         //以上是对象,再来看基本类型
  22.         int i1 = 1;
  23.         Integer i2 = 1;
  24.         Integer i = new Integer(1);
  25.         Integer j = new Integer(1);
  26.         Integer k = new Integer(2);
  27.         //只要是基本类型,不管值还是包装成对象,都是直接比较大小
  28.         System.out.println(i.equals(i1));  //比较的是值
  29.         System.out.println(i==i1);  //拆箱 ,
  30.         // 封装对象i被拆箱,变为值比较,1==1成立
  31.         //相当于 System.out.println(1==1);
  32.         System.out.println(i.equals(j));  //
  33.         System.out.println(i==j);   //  比较的是地址,这是俩对象
  34.         System.out.println(i2 == i); // i2在常量池里,i在堆里,地址不一样
  35.         System.out.println(i.equals(k));  //1和2,不解释
  36.     }
  37. }
复制代码
结论:

  • “==”比较的是什么?
    用于基本数据(8种)类型(或包装类型)相互比较,比较二者的值是否相等。
    用于引用数据(类、接口、数组)类型相互比较,比较二者地址是否相等。
  • equals比较的什么?
    默认情况下,所有对象继承Object,而Object的equals比较的就是内存地址
    所以默认情况下,这俩没啥区别
2) 内存地址生成与比较

tips:既然没区别,那我们看一下,内存地址到底是个啥玩意
目标:内存地址是如何来的?
Main.java
  1.     public static void main(String[] args) {
  2.         User  user1=new User("张三");
  3.         User  user2=new User("张三");
  4.     }
复制代码
1、加载过程(回顾)
从java文件到jvm:

tips: 加载到方法区
这个阶段只是User类的信息进入方法区,还没有为两个user来分配内存
2、分配内存空间
在main线程执行阶段,指针碰撞(连续内存空间时),或者空闲列表(不连续空间)方式开辟一块堆内存
每次new一个,开辟一块,所以两个new之间肯定不是相同地址,哪怕你new的都是同一个类型的class。
那么它如何来保证内存地址不重复的呢?(cas画图)

3、指向
在栈中创建两个局部变量 user1,user2,指向堆里的内存
归根到底,上面的==比较的是两个对象的堆内存地址,也就是栈中局部变量表里存储的值。
  1. public boolean equals(Object obj) {
  2.     return (this == obj);//本类比较的是内存地址(引用)
  3. }
复制代码
3) 默认equals的问题

需求(or 目标):user1和user2,如果name一样我们就认为是同一个人;如何处理?
tips:
面试最常问的问题
1、equals比较的什么?
2、有没有重写过equals?
3、有没有重写过hashCode?
4、什么情况下需要重写equals()和hashCode()?
1、先拿User下手,看看它的默认行为com.eq.EqualsObjTest
  1.     public static void main(String[] args) {
  2.        //需求::user1和user2,在现实生活中是一个人;如何判定是一个人(相等)
  3.         User user1 = new User("张三");
  4.         User user2 = new User("张三");
  5.         System.out.println("是否同一个人:"+user1.equals(user2));
  6.         System.out.println("内存地址相等:"+String.valueOf(user1 == user2));//内存地址
  7.         System.out.println("user1的hashCode为>>>>" + user1.hashCode());
  8.         System.out.println("user2的hashCode为>>>>" + user2.hashCode());
  9.     }
复制代码
输出如下

结论:
很显然,默认的User继承了Object的方法,而object,根据上面的源码分析我们知道,equals就是内存地址。
而你两次new User,不管name怎么一致,内存分配,肯定不是同一个地址!
怎么破?
2、同样的场景,我们把用户名从User换成单纯的字符串试试com.eq.EqualsStrTest
  1. public static void main(String[] args) {
  2.         String str1 = "张三";//常量池
  3.         String str2 = new String("张三");//堆中
  4.         String str3 = new String("张三");//堆中
  5.         System.out.println("是否同一人:"+str1.equals(str2));//这个地方为什么相等呢,重写
  6.         System.out.println("是否同一人:"+str2.equals(str3));//这个地方为什么相等呢,重写
  7.         //如果相等,hashcode必须相等,重写
  8.         System.out.println("str1的hashCode为>>" + str1.hashCode());
  9.         System.out.println("str2的hashCode为>>" + str2.hashCode());
  10.     }
  11. }
复制代码
输出如下

达到了我们的逾期,相同的name,被判定为同一个人,为什么呢?往下看!
String的源码分析
  1.     /**
  2.      * Compares this string to the specified object.  The result is {@code
  3.      * true} if and only if the argument is not {@code null} and is a {@code
  4.      * String} object that represents the same sequence of characters as this
  5.      * object.
  6.      *
  7.      * @param  anObject
  8.      *         The object to compare this {@code String} against
  9.      *
  10.      * @return  {@code true} if the given object represents a {@code String}
  11.      *          equivalent to this string, {@code false} otherwise
  12.      *
  13.      * @see  #compareTo(String)
  14.      * @see  #equalsIgnoreCase(String)
  15.      */
  16.     public boolean equals(Object anObject) {
  17.               //如果内存地址相等,那必须equal
  18.         if (this == anObject) {
  19.             return true;
  20.         }
  21.         if (anObject instanceof String) {
  22.                   //如果对象是String类型
  23.             String anotherString = (String)anObject;
  24.             int n = value.length;
  25.             if (n == anotherString.value.length) {
  26.                       //并且长度还相等!
  27.                 char v1[] = value;
  28.                 char v2[] = anotherString.value;
  29.                 int i = 0;
  30.                       //那我们就逐个字符的比较
  31.                 while (n-- != 0) {
  32.                           //从前往后,任意一个字符不匹配,直接返回false
  33.                     if (v1[i] != v2[i])
  34.                         return false;
  35.                     i++;
  36.                 }
  37.                       //全部匹配结束,返回true
  38.                 return true;
  39.             }
  40.         }
  41.         return false;
  42.     }
复制代码
结论:
String类型改写了equals方法,没有使用Object的默认实现
它不管你是不是同一个内存地址,只要俩字符串里的字符都匹配上,那么equals就认为它是true
3、据此,我们参照String,来重写User的equals和hashCodecom.eq.User2
  1.     @Override
  2.     public boolean equals(Object o) {
  3.               //注意这些额外的判断类操作
  4.         if (this == o) return true;
  5.         if (o == null || getClass() != o.getClass()) return false;
  6.         User user = (User) o;
  7.         //比较值
  8.         return name != null ? name.equals(user.name) : user.name == null;
  9.     }
  10.     @Override
  11.     public int hashCode() {
  12.         //返回值的hashCode
  13.         return name != null ? name.hashCode() : 0;
  14.     }
复制代码
换成User2 再来跑试试 (参考 com.eq.EqualsObjTest2)

目的达到!
4)hashCode与equals

为什么说hashCode和equals是一对搭档?他俩到底啥关系需要绑定到一块?
看代码说话:(com.eq.Contains)
  1. package com.eq;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. public class Contains {
  5.     public static void main(String[] args) {
  6.         User user1 = new User("张三");
  7.         User user2 = new User("张三");
  8.         Set set = new HashSet();
  9.         set.add(user1);
  10.         System.out.println(set.contains(user2));
  11.         User2 user3 = new User2("张三");
  12.         User2 user4 = new User2("张三");
  13.         Set set2 = new HashSet();
  14.         set2.add(user3);
  15.         System.out.println(set2.contains(user4));
  16.     }
  17. }
复制代码
结论:
hashCode是给java集合类的一些动作提供支撑,来判断俩对象“是否是同一个”的标准
equals是给你编码时判断用的,所以,这俩必须保持一致的逻辑。
5)总结

1、特殊业务需求需要重写,比如上面的
2、例如map,key放自定义对象也需要重写
3、重写equals后必须要重写hashCode,要保持逻辑上的一致!
1.2.5 关于双等(扩展)

equals被重写后,双等还留着干啥用?
1)String的特殊性

tips:面试常问的问题
intern是做什么的?
先来看一段代码:(com.eq.Intern)
  1. public class Intern {
  2.     public static void main(String[] args) {
  3.         String str1 = "张三";//常量池
  4.         String str2 = new String("张三");//堆中
  5.         //intern;内存地址是否相等(面试常问)
  6.         System.out.println("str1与str2是否相等>>" +(str1==str2));  // false
  7.         System.out.println("str1与str2是否相等>>" +(str1==str2.intern()));  // true
  8.     }
  9. }
复制代码

版本声明:(JDK1.8)
new String是在堆上创建字符串对象。
当调用 intern() 方法时,
JVM会将字符串添加(堆引用指向常量池)到常量池中
注意:
1、1.8版本只是将hello word在堆中的引用指向常量池,之前的版本是把hello word复制到常量池
2、堆(字符串常量值)      方法区(运行时常量池)不要搞反了
2)valueOf里的秘密

关于双等号地址问题,除了String.intern() , 在基础类型里,如Integer,Long等同样有一个方法:valueOf需要注意
我们先来看一个小例子: 猜一猜结果?
  1. package com.eq;
  2. public class Valueof {
  3.     public static void main(String[] args) {
  4.         System.out.println( Integer.valueOf(127) == Integer.valueOf(127));
  5.         System.out.println( Integer.valueOf(128) == Integer.valueOf(128));
  6.     }
  7. }
复制代码
奇怪的结果……
源码分析(以Integer为例子):
[code]    /**     * Returns an {@code Integer} instance representing the specified     * {@code int} value.  If a new {@code Integer} instance is not     * required, this method should generally be used in preference to     * the constructor {@link #Integer(int)}, as this method is likely     * to yield significantly better space and time performance by     * caching frequently requested values.     *     * !在-128 到 127 之间会被cache,同一个地址下,超出后返回new对象!     *     * This method will always cache values in the range -128 to 127,     * inclusive, and may cache other values outside of this range.     *     * @param  i an {@code int} value.     * @return an {@code Integer} instance representing {@code i}.     * @since  1.5     */    public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

玛卡巴卡的卡巴卡玛

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表