当前位置:网站首页>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
边栏推荐
- Tower of Hanoi II | tower of Hanoi 4 columns
- SPARK中 DS V2 push down(下推)的一些说明
- Cause: couldn‘t make a guess for 解决方法
- Uniapp "no mobile phone or simulator detected, please try again later" and uniapp custom components and communication
- 输入整数后输入整行字符串的解决方法
- Okaleido生态核心权益OKA,尽在聚变Mining模式
- Production of a-modal drag function in antui
- 时间序列异常检测
- Network related journals and conferences in CS
- Netease cloud UI imitation -- & gt; sidebar
猜你喜欢
Review of database -- 1. Overview
Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
【有奖提问】向图灵奖得主、贝叶斯网络之父 Judea Pearl 提问啦
【Halcon视觉】形态学膨胀
SQL优化的魅力!从 30248s 到 0.001s
Cause: could't make a guess for solution
【Halcon视觉】阈值分割
Introduction to latex, EPS picture bounding box
【Halcon视觉】仿射变换
Draw arrows with openlayer
随机推荐
Leetcode 504. Hex number
Yarn 'TSC' is not an internal or external command, nor is it a runnable program or batch file. The problem that the command cannot be found after installing the global package
Time series anomaly detection
PLC概述
Some descriptions of DS V2 push down in spark
Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component
PTA class a 1001
Force deduction DFS
微信公众号发布提醒(微信公众号模板消息接口)
Study notes of the second week of sophomore year
Rowselection emptying in a-table
数通基础-TCPIP参考模型
Solution of inputting whole line string after inputting integer
Common errors when starting projects in uniapp ---appid
Study notes of the third week of sophomore year
Draco developed by Google and Pixar supports USD format to accelerate 3D object transmission & lt; Forward & gt;
Interview shock 68: why does TCP need three handshakes?
What is wrong about the description of function templates (how to solve link format errors)
Vectortilelayer replacement style
Jpg to EPS