== VS equals()

==
  • 基础类型: ==比较的是值
  • 引用类型: ==比较的是对象的内存地址
equals()

equals()只能比较引用类型,无法比较基础类型.equals()方法在顶级父类Object中,代码如下:

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

可以看出这个代码就是判断是否是同一对象.那么,当子类重写 equals()往往都是将属性内容相同的对象认为是同一对象,
如果子类不直接或间接重写Objectequals()方法,那么调用的equals()==相同.

String a = new String("aa"); // a 为一个引用
String b = new String("aa"); // b为另一个引用,对象的内容一样
String aa = "aa"; // 放在常量池中
String bb = "aa"; // 从常量池中查找
System.out.println(aa == bb);// true
System.out.println(a == b);// false
System.out.println(a.equals(b));// true

上面代码的String重写了equals(),代码如下:

public boolean equals(Object anObject) {if (this == anObject) {return true;}if (anObject instanceof String) {String anotherString = (String)anObject;int n = value.length;if (n == anotherString.value.length) {char v1[] = value;char v2[] = anotherString.value;int i = 0;while (n-- != 0) {if (v1[i] != v2[i])return false;i++;}return true;}}return false;}

hashCode() VS equals()

  • hashCode()函数返回哈希码,确定该对象在哈希表中的索引位置.同样属于Object类中,代码如下:public native int hashCode();,native调用C/C++,返回int哈希码.利用哈希码能够快速检索出对象
    HashSet/HashMap会先调用hashCode(),如果哈希码不同,直接判断对象不同,否则进行下面的equals()操作,大大减少了equals()的操作,提高执行速度.(C/C++本身比Java执行快,equals()执行也比hashCode()逻辑复杂)
  • hashCode()返回值相同也不能认为是同一对象,存在hash冲突
  • hashCode 相同,equals()为true才能认为是同一对象
为什么重写 equals() 时必须重写 hashCode() 方法?
  • 正面:两对象相等,那么hashCode也相等,equals()也为true
  • 反面:重写 equals(),但是不重写hashCode(),会导致equals(),判断是同一个对象,但是哈希码并不同
  • 例子: 重写了equals()方法,不重写hashCode(),同一名学生,添加到hashSet中时候,会添加两次,因为你只是通过属性内容判断的是否为同一对象!!!

包装类型的常量池

  • Byte/Short/Integer/Long 这 4 种包装类默认创建了数值 [-128,127] 的相应类型的缓存数据
  • Character 创建了数值在 [0,127] 范围的缓存数据
  • Boolean 直接true/false
    源代码如下:
private static class ByteCache {private ByteCache(){}static final Byte cache[] = new Byte[-(-128) + 127 + 1];static {for(int i = 0; i < cache.length; i++)cache[i] = new Byte((byte)(i - 128));}
}/*** Returns a {@code Byte} instance representing the specified* {@code byte} value.* If a new {@code Byte} instance is not required, this method* should generally be used in preference to the constructor* {@link #Byte(byte)}, as this method is likely to yield* significantly better space and time performance since* all byte values are cached.** @param  b a byte value.* @return a {@code Byte} instance representing {@code b}.* @since  1.5*/public static Byte valueOf(byte b) {final int offset = 128;return ByteCache.cache[(int)b + offset];}
private static class ShortCache {private ShortCache(){}static final Short cache[] = new Short[-(-128) + 127 + 1];static {for(int i = 0; i < cache.length; i++)cache[i] = new Short((short)(i - 128));}
}/*** Returns a {@code Short} instance representing the specified* {@code short} value.* If a new {@code Short} instance is not required, this method* should generally be used in preference to the constructor* {@link #Short(short)}, as this method is likely to yield* significantly better space and time performance by caching* frequently requested values.** This method will always cache values in the range -128 to 127,* inclusive, and may cache other values outside of this range.** @param  s a short value.* @return a {@code Short} instance representing {@code s}.* @since  1.5*/public static Short valueOf(short s) {final int offset = 128;int sAsInt = s;if (sAsInt >= -128 && sAsInt <= 127) { // must cachereturn ShortCache.cache[sAsInt + offset];}return new Short(s);}
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h = 127;String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if (integerCacheHighPropValue != null) {try {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1);} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.}}high = h;cache = new Integer[(high - low) + 1];int j = low;for(int k = 0; k < cache.length; k++)cache[k] = new Integer(j++);// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high >= 127;}private IntegerCache() {}}/*** 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.** 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 <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}
private static class LongCache {private LongCache(){}static final Long cache[] = new Long[-(-128) + 127 + 1];static {for(int i = 0; i < cache.length; i++)cache[i] = new Long(i - 128);}}/*** Returns a {@code Long} instance representing the specified* {@code long} value.* If a new {@code Long} instance is not required, this method* should generally be used in preference to the constructor* {@link #Long(long)}, as this method is likely to yield* significantly better space and time performance by caching* frequently requested values.** Note that unlike the {@linkplain Integer#valueOf(int)* corresponding method} in the {@code Integer} class, this method* is <em>not</em> required to cache values within a particular* range.** @param  l a long value.* @return a {@code Long} instance representing {@code l}.* @since  1.5*/public static Long valueOf(long l) {final int offset = 128;if (l >= -128 && l <= 127) { // will cachereturn LongCache.cache[(int)l + offset];}return new Long(l);}

上面的缓存代码可以完美解释下面的结果:

Integer a = 10;
Integer b = 10;
System.out.println(a == b);// 输出 trueFloat c = 10f;
Float d = 10f;
System.out.println(c == d);// 输出 falseDouble e = 1.2;
Double f = 1.2;
System.out.println(e == f);// 输出 false
Integer a = 10;
Integer b = new Integer(10);
System.out.println(a==b);// false
//Integer a = 10;=>Integer a=Integer.valueOf(10);使用常量池中的对象,Integer b = new Integer(10);创建新对象

自动装箱与拆箱

从字节码中,我们发现装箱其实就是调用了 包装类的valueOf()方法,拆箱其实就是调用了 xxxValue()方法。

  • Integer i = 1 等价于 Integer i = Integer.valueOf(1)
  • int n = i 等价于 int n = i.intValue();
  • 如果频繁拆装箱的话,也会严重影响系统的性能。我们应该尽量避免不必要的拆装箱操作。

hashCode() vs equals() vs ==相关推荐

  1. hashcode的作用_看似简单的hashCode和equals面试题,竟然有这么多坑!

    hashCode()方法和equals()区别与联系这到面试题,看似简单,根据以往面试星友的情况来说,绝大部分人都不能很好的回答出来,要么没有逻辑,想到一句就说一句,要么抓不住重点,答非所问.从这个很 ...

  2. 理解Java中的hashCode 和 equals 方法

    2019独角兽企业重金招聘Python工程师标准>>> 在Java里面所有的类都直接或者间接的继承了java.lang.Object类,Object类里面提供了11个方法,如下: 1 ...

  3. java中Object类的hashCode和equals及toString方法。

    java中的hashcode.equals和toString方法都是基类Object的方法. 首先说说toString方法,简单的总结了下API说明就是:返回该对象的字符串表示,信息应该是简明但易于读 ...

  4. 为什么使用HashMap需要重写hashcode和equals方法_为什么要重写 hashcode 和 equals 方法?...

    1. 通过Hash算法来了解HashMap对象的高效性 2. 为什么要重写equals和hashCode方法 3. 对面试问题的说明 <Java 2019 超神之路> <Dubbo ...

  5. HashMap存自定义对象为什么要重写 hashcode 和 equals 方法?

    HashMap的k放过自定义对象么? 当我们把自定义对象存入HashMap中时,如果不重写hashcode和equals这两个方法,会得不到预期的结果. class Key{private Integ ...

  6. (转)从一道面试题彻底搞懂hashCode与equals的作用与区别及应当注意的细节

    背景:学习java的基础知识,每次回顾,总会有不同的认识.该文系转载 最近去面试了几家公司,被问到hashCode的作用,虽然回答出来了,但是自己还是对hashCode和equals的作用一知半解的, ...

  7. java中hashcode()和equals()的详解[转]

    今天下午研究了半天hashcode()和equals()方法,终于有了一点点的明白,写下来与大家分享(zhaoxudong 2008.10.23晚21.36).  1. 首先equals()和hash ...

  8. 【面试题】hashCode() 和 equals() 之间的关系

    前言 关于 hashCode 和 equals 的处理,遵循如下规则: 只要重写 equals,就必须重写 hashCode 因为 Set 存储的是不重复的对象,依据 hashCode 和 equal ...

  9. 为什么要重写 hashcode 和 equals 方法?

    我在面试Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候选人直接说没写过.我就想,或许真的没写过,于是就再通过一个问题确认:你在用HashMap的时候,键(Key)部分,有 ...

  10. 为什么使用HashMap需要重写hashcode和equals方法_为什么要重写hashcode和equals方法?你能说清楚了吗...

    我在面试Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候选人直接说没写过.我就想,或许真的没写过,于是就再通过一个问题确认:你在用HashMap的时候,键(Key)部分,有 ...

最新文章

  1. std::bind介绍
  2. 从 NavMesh 网格寻路回归到 Grid 网格寻路。
  3. 混淆工具Dotfuscator基本使用
  4. Python实现命令行监控北京实时公交之一
  5. 如何开发一个异常检测系统:如何评价一个异常检测算法
  6. 在Visual Studio中利用NTVS创建Pomelo项目
  7. html没有内容怎么爬,Url没有在网页中返回正确的html(对于我的Java爬虫)
  8. MediaInfo源代码分析 3:Open()函数
  9. socket怎么同时监听两个端口_三十岁了,我同时爱上两个男人,我现在不知道怎么办...
  10. 用java求解八枚银币问题_算法笔记_004:8枚硬币问题【减治法】
  11. DOS MASM 安装
  12. 郑州大学python考试题库_GitHub - 2512500960/zzu-minieap: 适用于郑州大学的minieap,锐捷认证客户端,用于linux(包括openwrt)平台,...
  13. python画航线图_pyecharts绘制geo地图
  14. html css javascript jdk 等离线开发手册
  15. mysql etimedout_ETIMEDOUT
  16. oracle redo 状态,理解ORACLE REDO与UNDO
  17. 一键seo提交收录_百度网站提交,选择主动提交,还是被动收录?
  18. 计算机网络跳槽自荐信,计算机网络应用专业求职自荐信范文
  19. Rust中的所有权和借用的关系图
  20. 为程序员提供一杯免费咖啡

热门文章

  1. oracle12c创建监听,Oracle 12c为PDB创建专用监听
  2. c# Queue源码解析
  3. 数据结构软件测试,资讯详情-java常见数据结构-柠檬班-自动化测试-软件测试培训-自学官网...
  4. Dynamics finance and operation官方虚拟机10.0.24使用私人账号访问
  5. Python3 获取法定节假日
  6. 学java,报班还是自学?
  7. 如何在vue中优雅的使用ocx控件:结合iframe
  8. pythontrun什么意思_python 新手笔记一
  9. Unity3d:UGUI,UI与特效粒子层级,2018.2以上版本BakeMesh,粒子在两个Image之间且在ScrollView
  10. windows电脑打开jnlp文件设置