
== 的本质:对对象类型(如 Integer)而言,== 比较的是内存地址(即是否为同一个对象),而非实际值 。equals() 的作用:Integer 重写了 equals() 方法,直接比较整数值是否相等,与对象引用无关 。示例:
Integer a = 200;
Integer b = 200;
System.out.println(a == b); // false(引用不同)
System.out.println(a.equals(b)); // true(值相同)Java 对 Integer 对象在 -128 到 127 范围内进行了缓存优化,自动装箱(如 Integer a = 100)会复用缓存对象,此时 == 可能返回 true;但超出此范围时,每次自动装箱会创建新对象,导致 == 失效 。
示例:
Integer c = 100;
Integer d = 100;
System.out.println(c == d); // true(缓存范围内)
Integer e = 200;
Integer f = 200;
System.out.println(e == f); // false(超出缓存范围,创建新对象)new 的干扰即使数值在缓存范围内,显式使用 new 关键字 会强制创建新对象,== 比较必定返回 false 。
Integer g = new Integer(100);
Integer h = new Integer(100);
System.out.println(g == h); // false(不同对象)当 Integer 与 int 比较时,Integer 会自动拆箱为 int,此时 == 比较的是值,可能掩盖对象比较的问题,但需注意 空指针风险 。
Integer i = null;
int j = 100;
System.out.println(i == j); // 抛出 NullPointerException(自动拆箱导致)<!--br {mso-data-placement:same-cell;}--> td {white-space:nowrap;border:0.5pt solid #dee0e3;font-size:10pt;font-style:normal;font-weight:normal;vertical-align:middle;word-break:normal;word-wrap:normal;}
场景 | == 结果 | 推荐方法 |
|---|---|---|
缓存范围内自动装箱(-128~127) | 可能为 true | 仍优先用 equals |
缓存范围外自动装箱 | FALSE | 必须用 equals |
显式 new 创建对象 | FALSE | 必须用 equals |
与 int 比较 | 自动拆箱(值比较) | 需判空避免异常 |
最佳实践:
equals() 比较 Integer 对象的值 null 时,优先用 Objects.equals(a, b) 避免空指针 == 和自动拆箱,尤其是对可能为 null 的 Integer 对象 通过理解这些机制,可避免因 == 误用导致的逻辑错误和性能问题
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。