当前位置:网站首页>equals与==的区别
equals与==的区别
2022-07-26 10:16:00 【才哈哈】
先说结论:
在Java中 equals 与 == 都是用来判断两个数据是否相等,且都有自己的应用场景。
先说逻辑运算符 == ,对于基本数据类型来说,它比较的是值,对于引用类型来说,它比较的是对象的内存地址,即判断两个引用是否指向堆内存中同一个对象。由于Java语言只有值传递,所以对于 == 来说,比较的都是值(只不过基本数据类型的值是值本身,而引用类型的值是对象地址);
equals是Object类中的成员方法,每个类都可以重写该方法,如果自定义的类中没有重写equals方法,它将继承Object类equals方法,其作用与逻辑运算符 == 相同。
实际应用中,自定义类中往往会重写Object类equals方法,一般用来比较两个独立对象的内容是否相同(要看具体方法的实现)。
我们通过一个简单的内存模型来具体分析:
图中a与b为基本数据类型(int a = 5 ,int b = 5);
str1与str2为String类型(String类中重写了Object类中的equals成员方法);
user1与user2为自定义类对象(该类中没有重写equals方法,用来与String类型的值做参照,验证上述结论)
代码实现:
/** * 测试类 */
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("张三");
User user2 = new User("张三");
//基本数据类型没有equals方法
System.out.println(a == b);//预期运行结果true
//String类重写了equals方法,用来比较两个独立对象的内容是否相同
System.out.println(str1 == str2);//预期运行结果false
System.out.println(str1.equals(str2));//预期运行结果true
//自定义类对象没有重写equals(逻辑运算符 ==与equals方法作用相同,预期运行结果一致)
System.out.println(user1 == user2);//预期运行结果false
System.out.println(user1.equals(user2));//预期运行结果false
}
}
/** * 自定义User类 */
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;
}
}
运行结果:
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
运行结果符合预期
拓展
自定义User类中也重写equals方法,我们再来看一下运行结果是否符合预期(养成一个良好的编程习惯,重写equals方法时也记得重写一下hashCode方法)
代码示例:
import java.util.Objects;
/** * 测试类 */
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("张三");
User user2 = new User("张三");
//基本数据类型没有equals方法
System.out.println(a == b);//预期运行结果true
//String类重写了equals方法,用来比较两个独立对象的内容是否相同
System.out.println(str1 == str2);//预期运行结果false
System.out.println(str1.equals(str2));//预期运行结果true
//自定义类对象也已重写equals方法
System.out.println(user1 == user2);//预期运行结果false
System.out.println(user1.equals(user2));//预期运行结果true
}
}
/** * 自定义User类已重写equals与hashCode方法 */
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);
}
}
运行结果:
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
运行结果符合预期
边栏推荐
- PHP one-time request lifecycle
- 30 minutes to thoroughly understand the synchronized lock upgrade process
- 服务器内存故障预测居然可以这样做!
- Transform between tree and array in JS (hide the children field if the child node of the tree is empty)
- Basic usage of protobuf
- 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
- Use of pclint in vs2013
- Okaleido生态核心权益OKA,尽在聚变Mining模式
- 简单化构造函数的继承方法(一)- 组合继承
- Using undertow, Nacos offline logout delay after service stop
猜你喜欢
Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install
【Halcon视觉】图像滤波
【Halcon视觉】阈值分割
点赞,《新程序员》电子书限时免费领啦!
Azkaban [basic knowledge 01] core concepts + features +web interface + Architecture +job type (you can get started with Azkaban workflow scheduling system in one article)
Employee information management system based on Web
Beginner of flask framework-04-flask blueprint and code separation
Data communication foundation - layer 2 switching principle
PMM (percona monitoring and management) installation record
论文笔记(SESSION-BASED RECOMMENDATIONS WITHRECURRENT NEURAL NETWORKS)
随机推荐
Basic usage of protobuf
Basics of data communication - basic knowledge of network
Wechat applet learning notes 2
Uniapp "no mobile phone or simulator detected, please try again later" and uniapp custom components and communication
时间序列异常检测
Interview shock 68: why does TCP need three handshakes?
数据库的复习--3.SQL语言
Learning about opencv (4)
Flask框架初学-03-模板
[Qualcomm][Network] qti服务分析
Keeping alive to realize MySQL automatic failover
Mysql5.7.25 master-slave replication (one-way)
数通基础-TCPIP参考模型
Sqoop [environment setup 01] CentOS Linux release 7.5 installation configuration sqoop-1.4.7 resolve warnings and verify (attach sqoop 1 + sqoop 2 Latest installation package +mysql driver package res
AirTest
【Halcon视觉】形态学腐蚀
Employee information management system based on Web
Sublime install plug-ins
面试突击68:为什么 TCP 需要 3 次握手?
Wechat H5 payment on WAP, for non wechat browsers