The difference between equals and = = in Java

RioTian 2021-06-23 23:37:41
difference equals java


Before that Java String comparison (3 Methods ) And contrast C++ What should I pay attention to when I'm doing this I wrote a little bit about equals() And == Comparison , But the latest Java In the process of examination review, we found that some situations were not involved , So learn again


When we write code, we often use equals and == To determine if two objects are equal , So what's the difference between the two , There are mainly the following differences :

  1. The first difference is ,equals Is the method , and == It's the operator ;

  2. For variables of basic type ( Such as shortintlongfloatdouble), Only use == , Because these basic types of variables don't have equals Method . For comparison of basic type variables , Use == Compare , The general comparison is their values .

  3. For variables of reference type ( for example String class ) Only then equals Method , because String Inherited Object class , equals yes Object General methods of classes . For comparison of objects of this type , By default , That is, there is no duplication Object Class equals Method , Use == and equals The comparison has the same effect , All are The comparison is where they are stored in memory . But for some classes , In order to meet their own business needs , Possible equals Methods are duplicated , Use this time equals Method comparison needs to see the specific situation , for example String class , Use equals Methods compare their values ;

It may be a bit complicated to understand the third point , Because here equals Method comparison needs to be discussed in two situations , One case is that the method is not overridden , The other is that the method is rewritten .

  • about equals Methods are not overridden . If the class does not override the method , So the default is Object Class method , Here are Object Class equals Method :

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

You can see from the source code , It uses == Compare , So in this case, the comparison is their storage address in memory .

  • about equals When a method is overridden . With String Class, for example , Here are String Class equals Method :

     @Override public boolean equals(Object other) {
    if (other == this) {
    return true;
    }
    if (other instanceof String) {
    String s = (String)other;
    int count = this.count;
    if (s.count != count) {
    return false;
    }
    if (hashCode() != s.hashCode()) {
    return false;
    }
    char[] value1 = value;
    int offset1 = offset;
    char[] value2 = s.value;
    int offset2 = s.offset;
    for (int end = offset1 + count; offset1 < end; ) {
    if (value1[offset1] != value2[offset2]) {
    return false;
    }
    offset1++;
    offset2++;
    }
    return true;
    } else {
    return false;
    }
    }
    

You can see from the source code , String Class copied equals Method , When using == Compare the memory storage address is not equal , Next we compare the contents of the string to see if equal , therefore String Class equals Method will compare whether the string contents of the two are the same . Let's take a look at the following example :

 String a = "Hello World";
String b = new String("Hello World");
String c = b; // reference
System.out.println("a == b:" + a == b); //false
System.out.println("b == c:" + b == c); //true
System.out.println("a == c:" + a == c); //false
System.out.println("a.equals(b):" + a.equals(b)); //true
System.out.println("b.equals(c):" + b.equals(c)); //true
System.out.println("a.equals(c):" + a.equals(c)); //true
The final print will be :
a == b:false
b == c:true
a == c:false
a.equals(b):true
b.equals(c):true
a.equals(c):true

because String b adopt new The way has opened up new heap memory , and String a = "Hello World" It's stored in the constant pool , The two Java There are different locations in memory , therefore a == b by false; and equals Method when the memory addresses of the two are different , We'll compare the values of the two , The value of both is "Hello World" , therefore a.equals(b) by true.


In addition, please think about the running result of the code below True、false

public class Java_epuals {
public static void main(String[] args) {
Integer i2 = 10;
Integer i3 = 10;
System.out.println(i2 == i3); // true
Integer i4 = 128;
Integer i5 = 128;
System.out.println(i4 == i5); // false
}
}

about i2 and i3 Comparison , Because variables are defined by i2(i3) = 10 Their variables will be placed in the constant area , The memory addresses of the two variables are the same .

here == return true.

So why i4 and i5 Is to return false Well ?

This is because Java in integer The range value should be in -128 To +127 ( Why? Integer Object scope (-128-127) Between ), And the value we give is 128 , In this case, the variable is not defined in the constant area . So the memory addresses of the two variables are different ,== return false

版权声明
本文为[RioTian]所创,转载请带上原文链接,感谢
https://javamana.com/2021/06/20210623233648759f.html

  1. Matrix architecture practice of Boshi fund's Internet open platform based on rocketmq
  2. 字节面试,我这样回答Spring中的循环依赖,拿下20k offer!
  3. Byte interview, I answer the circular dependence in spring like this, and get 20K offer!
  4. oracle 11g查看alert日志方法
  5. How to view alert log in Oracle 11g
  6. 手写Spring Config,最终一战,来瞅瞅撒!
  7. Handwritten spring config, the final battle, come and see!
  8. 用纯 JavaScript 撸一个 MVC 框架
  9. Build an MVC framework with pure JavaScript
  10. 使用springBoot实现服务端XML文件的前端界面读写
  11. Using springboot to read and write the front interface of server XML file
  12. 【Javascript + Vue】实现随机生成迷宫图片
  13. [Javascript + Vue] random generation of maze pictures
  14. 大数据入门:Hadoop伪分布式集群环境搭建教程
  15. Introduction to big data: Hadoop pseudo distributed cluster environment building tutorial
  16. 八股文骚套路之Java基础
  17. commons-collections反序列化利用链分析(3)
  18. Java foundation of eight part wensao routine
  19. Analysis of common collections deserialization utilization chain (3)
  20. dubbogo 社区负责人于雨说
  21. Yu Yu, head of dubbogo community, said
  22. dubbogo 社区负责人于雨说
  23. Yu Yu, head of dubbogo community, said
  24. 设计模式 选自《闻缺陷则喜》此书可免费下载
  25. The design pattern is selected from the book "you are happy when you hear defects", which can be downloaded free of charge
  26. xDAI被选为 Swarm 的侧链解决方案,将百倍降低 Swarm 网络Gas费
  27. L2 - 深入理解Arbitrum
  28. Xdai is selected as the side chain solution of swarm, which will reduce the gas cost of swarm network 100 times
  29. L2 - deep understanding of arbitrum
  30. Java全栈方向学习路线
  31. 设计模式学习04(Java实现)——单例模式
  32. Java full stack learning route
  33. Design pattern learning 04 (Java implementation) - singleton pattern
  34. Mybatis学习01:利用mybatis查询数据库
  35. Mybatis learning 01: using mybatis to query database
  36. Java程序员从零开始学Vue(01)- 前端发展史
  37. Java程序员从零开始学Vue(05)- 基础知识快速补充(html、css、js)
  38. Java programmers learn Vue from scratch
  39. Java programmers learn Vue from scratch (05) - quick supplement of basic knowledge (HTML, CSS, JS)
  40. 【Java并发编程实战14】构建自定义同步工具(Building-Custom-Synchronizers)
  41. [Java Concurrent Programming Practice 14] building custom Synchronizers
  42. 【源码分析】- 在SpringBoot中你会使用REST风格处理请求吗?
  43. [source code analysis] - do you use rest style to process requests in springboot?
  44. 框架篇:见识一下linux高性能网络IO+Reactor模型
  45. Framework: see Linux high performance network IO + reactor model
  46. 基础篇:JAVA.Stream函数,优雅的数据流操作
  47. 基础篇:异步编程不会?我教你啊!CompletableFuture(JDK1.8)
  48. Basic part: Java. Stream function, elegant data stream operation
  49. Basic: asynchronous programming won't? I'll teach you! CompletableFuture(JDK1.8)
  50. 技能篇:sed教程-linux命令
  51. 数据库篇:mysql内置函数
  52. Linux 主要的发行系统版本介绍
  53. 网络篇:朋友面试之https认证加密过程
  54. Skills: sed tutorial - Linux command
  55. Database: built in functions of MySQL
  56. Introduction of Linux main distribution system versions
  57. Network: friends interview: the encryption process of HTTPS authentication
  58. [Linux]经典面试题 - 系统管理 - 备份策略
  59. 解决java socket在传输汉字时出现截断导致乱码的问题
  60. [Linux] classic interview questions system management backup strategy