当前位置:网站首页>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
运行结果符合预期
边栏推荐
- Tableviewcell highly adaptive
- Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
- Set view dynamic picture
- Principle analysis and source code interpretation of service discovery
- The fourth week of summer vacation
- 句句解析js中的完美 / 缓冲运动框架(新手专用)
- Cause: could't make a guess for solution
- Strange Towers of Hanoi|汉诺塔4柱问题
- Phpexcel export Emoji symbol error
- 如何写一篇百万阅读量的文章
猜你喜欢

Data communication foundation STP principle

Cause: couldn‘t make a guess for 解决方法

Draw arrows with openlayer

【Halcon视觉】阈值分割

Common errors when starting projects in uniapp ---appid

Beginner of flask framework-04-flask blueprint and code separation

【Halcon视觉】形态学腐蚀

Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
![[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks](/img/0f/01d6e49fff80a325b667784e40bff3.png)
[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks

分布式网络通信框架:本地服务怎么发布成RPC服务
随机推荐
Draw arrows with openlayer
Study notes at the end of summer vacation
Sqoop [put it into practice 02] sqoop latest version full database import + data filtering + field type support description and example code (query parameter and field type forced conversion)
Time series anomaly detection
Docker configuring MySQL Cluster
AirTest
Installation and use of cocoapods
Show default image when wechat applet image cannot be displayed
Study notes of the fifth week of sophomore year
Principle analysis and source code interpretation of service discovery
面试第一家公司的面试题及答案(一)
The problem of incomplete or partial display of the last recyclerview is solved
Employee information management system based on Web
protobuf的基本用法
点赞,《新程序员》电子书限时免费领啦!
Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component
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
【Halcon视觉】软件编程思路
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
Study notes of the first week of sophomore year