当前位置:网站首页>The difference between equals and = =
The difference between equals and = =
2022-07-26 10:21:00 【Haha】
Say first conclusion :
stay Java in equals And == Both are used to judge whether two data are equal , And they all have their own application scenarios .
Let's start with logical operators == , For basic data types , It compares values , For reference types , It compares the memory address of the object , Judgment Two quotes Whether to point to the same object in heap memory . because Java Language only has value passing , So for == Come on , The comparison is all worth ( Only the value of the basic data type is the value itself , The value of the reference type is the object address );
equals yes Object Class member methods , Every class can override this method , If there is no override in the custom class equals Method , It will inherit Object class equals Method , Its function is similar to that of logical operators == identical .
Practical application , Custom classes often override Object class equals Method , It is generally used to compare whether the contents of two independent objects are the same ( It depends on the implementation of specific methods ).
We analyze it concretely through a simple memory model :
In the figure a And b Is the basic data type (int a = 5 ,int b = 5);
str1 And str2 by String type (String class Object Class equals Member method );
user1 And user2 For custom class objects ( There is no override in this class equals Method , Used with String The value of type is used as a reference , Verify the above conclusion )

Code implementation :
/** * Test class */
public class Demo {
public static void main(String[] args) {
int a = 5;
int b = 5;
String str1 = new String("abc");
String str2 = new String("abc");
User user1 = new User(" Zhang San ");
User user2 = new User(" Zhang San ");
// Basic data type does not equals Method
System.out.println(a == b);// Expected operating results true
//String Class overridden equals Method , Used to compare whether the contents of two independent objects are the same
System.out.println(str1 == str2);// Expected operating results false
System.out.println(str1.equals(str2));// Expected operating results true
// Custom class objects are not overridden equals( Logical operators == And equals The method works the same , The expected operation results are consistent )
System.out.println(user1 == user2);// Expected operating results false
System.out.println(user1.equals(user2));// Expected operating results false
}
}
/** * Customize User class */
class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Running results :
D:\installPath\Java\jdk1.8.0_121\bin\java.exe "-javaagent:D:\installPath\IntelliJ IDEA 2019.1.4\lib\idea_rt.jar
true
false
true
false
false
Process finished with exit code 0
The running result is in line with the expectation
expand
Customize User Class is also overridden equals Method , Let's see whether the running results meet the expectations ( Develop a good programming habit , rewrite equals Method, also remember to rewrite hashCode Method )
Code example :
import java.util.Objects;
/** * Test class */
public class Demo {
public static void main(String[] args) {
int a = 5;
int b = 5;
String str1 = new String("abc");
String str2 = new String("abc");
User user1 = new User(" Zhang San ");
User user2 = new User(" Zhang San ");
// Basic data type does not equals Method
System.out.println(a == b);// Expected operating results true
//String Class overridden equals Method , Used to compare whether the contents of two independent objects are the same
System.out.println(str1 == str2);// Expected operating results false
System.out.println(str1.equals(str2));// Expected operating results true
// Custom class objects have also been overridden equals Method
System.out.println(user1 == user2);// Expected operating results false
System.out.println(user1.equals(user2));// Expected operating results true
}
}
/** * Customize User Class overridden equals And hashCode Method */
class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
Running results :
D:\installPath\Java\jdk1.8.0_121\bin\java.exe "-javaagent:D:\installPath\IntelliJ IDEA 2019.1.4\lib\idea_rt.jar
true
false
true
false
true
Process finished with exit code 0
The running result is in line with the expectation
边栏推荐
- RecyclerView最后一条显示不全或显示部分的问题解决
- Employee information management system based on Web
- Like, "new programmer" e-book is free for a limited time!
- Uniapp common error [wxml file compilation error]./pages/home/home Wxml and using MySQL front provided by phpstudy to establish an independent MySQL database and a detailed tutorial for independent da
- Introduction to latex, EPS picture bounding box
- Learning about opencv (1)
- C language course design Tetris (Part 1)
- 我们的Web3创业项目,黄了
- Redis realizes the correct posture of token bucket
- Draw arrows with openlayer
猜你喜欢

Meeting OA project (III) -- my meeting (meeting seating and submission for approval)

新建福厦铁路全线贯通 这将给福建沿海带来什么?

The practice of OpenCV -- bank card number recognition

Learning about tensorflow (II)

30分钟彻底弄懂 synchronized 锁升级过程

【Halcon视觉】算子的结构
![[Qualcomm][Network] qti服务分析](/img/76/49054ff8c7215eca98cc479ab1d986.png)
[Qualcomm][Network] qti服务分析

Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install

点赞,《新程序员》电子书限时免费领啦!

Deduct daily question 838 of a certain day
随机推荐
SQL Server 2008 server engine failed to start?
点赞,《新程序员》电子书限时免费领啦!
2022/07/25------字符串的排列
Uniapp error 7 < Map >: marker ID should be a number
Some descriptions of DS V2 push down in spark
AirTest
Closure of go (cumulative sum)
Learning about opencv (4)
Netease cloud UI imitation -- & gt; sidebar
On the compilation of student management system of C language course (simple version)
INSTALL_FAILED_SHARED_USER_INCOMPATIBLE错误解决方式
面试突击68:为什么 TCP 需要 3 次握手?
Replay the snake game with C language (II) end
【杂谈】Error loading psycopg2 module :No module named psycopg2
C language course design Tetris (Part 1)
数通基础-二层交换原理
El table implements adding / deleting rows, and a parameter changes accordingly
Production of a-modal drag function in antui
Reproduce the snake game in C language (I) build pages and construct snakes
PTA class a 1002