当前位置:网站首页>Interviewer: please talk about = = operator and equals (), from the perspective of basic data type and reference data type
Interviewer: please talk about = = operator and equals (), from the perspective of basic data type and reference data type
2022-04-22 15:40:00 【I am a cabbage】
Hello everyone , I'm cabbage , You can call me vegetable ( Worthy of the name, it belongs to , ha-ha ~), A sophomore . This article is mainly about java Interview questions :== Operators, and equals() Knowledge points of . If you get something after reading the article , You can support bloggers three times in a row ~, Hee hee .
List of articles
One 、 Preface
Understand the difference between them , First of all, we need to understand their definitions .
- When comparing reference data types ,
==The comparison is whether the memory address of the variable is the same , That is, whether it points to the same object , Is the real pointer operation . equals()Whether the two objects are the same , Because all classes inheritjava.lang.ObjectClass , So it applies to all objects , If the method is not covered , The call is still Object Methods in class , and Object Medium equals Method returns==The judgment of the .- in other words
==Is a pointer operation , Used to compare equal values , and equals Is a method , stay Object Class equals Method is actually==, If subclasses don't override equals Method , The two are no different .
Two 、 The source code parsing
Have a look first Object Class :

You can see it in the source code , The two compare the address value .
Look again. String Class :

You can see it in the source code ,String Class overridden Object Class equals Method , First determine the addresses of the two , If equal , Go straight back true; Otherwise , Then judge whether the parameter is String Type of , If it is , Just compare the contents of each character one by one , The final result .
Finally, let's look at Integer Class source code :

You can know from the source code , First, judge whether the parameter is Integer Type of ; If it is , Will call intValue(), Get the value of this parameter , Finally, the two are compared ; In a nutshell , They end up comparing numbers .
3、 ... and 、 Comparison of basic data types
For the basic data type of , Only == The operator , Because the basic data type is not an object , No inheritance Object class , Naturally, you can't rewrite equals Method . It should be noted that , In the use of == When the operator , Automatic type conversion occurs , Look at the following code :
public void test1() {
int i = 10;
int j = 10;
double d = 10.0;
System.out.println(i == j);//true
System.out.println(i == d);//true
boolean b = true;
// System.out.println(i == b); There will be errors in compilation
char c = 10;
System.out.println(i == c);//true
System.out.println(c == d);//true
char c1 = 'A';
char c2 = 65;
System.out.println(c1 == c2);//true
}
Four 、 Reference data type comparison
In the use of reference data types , The most common is String The class , So let's take a look at the following code , Try to think about the results of the run :
public void test2() {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
System.out.println(s1 == str1);
System.out.println(s1.equals(str1));
}
The end result is :true、true、false、true、false、true
- First look at the first half of the code ,
s1 == s2The result is true, Because the value of the string is final, Its value is immutable , There is only one copy in memory , therefore s1 and s2 The address value of is the same . - Finally, look at the second half of the code , because str1 and str2 Keyword used new, That is, two pieces of space are opened up in memory , Their address values are different , therefore str1 == str2 The result is false.
Let's look at the last set of code :
public void test3() {
int a = 10;
Integer b = new Integer(10);
Integer c = new Integer(10);
System.out.println(b == c);
System.out.println(a == c);
System.out.println(b.equals(c));
System.out.println(c.equals(a));
}
The result of the operation is :false、true、true、true
- about
a==cWhy does this return true Well ? Are variables a and c Is the memory address stored the same ? This is obviously not true , After all a It's the basic data type , The stored address is the address in the stack , and c Is the reference data type , The storage address should point to the address in the alignment . This is because when Integer And int Conduct==When comparing ,Integer Will be unpacked into one int type , So it's still equivalent to two int Compare types , there Integer, Whether it's direct assignment , still new Objects created , Just follow int Comparison will unpack for int type , So it's equal . In fact, all wrapper classes are related to their basic data types==The box will be opened automatically during comparison .
5、 ... and 、 Custom implementation equals Method
So here comes the question , If we want to write our own class , Also want to rewrite equals How to do it ? It's very simple , Use Alt+insert Then select as shown in the figure :
Write a code test :
public void test4() {
Person person1 = new Person("cabbage",20);
Person person2 = new Person("cabbage",20);
System.out.println(person1.equals(person2));
}
If the run result returns true, So congratulations , succeed ~
6、 ... and 、 Summary
- When used equals() When comparing methods , Antitype File、String、Date And packaging , Is to compare the type and content without considering whether the reference is the same object ; Because in these classes, you override Object Class equals() Method .
- Finally, give a reference answer :

Thank you for reading , Progress together , Hee hee ~
版权声明
本文为[I am a cabbage]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221536515633.html
边栏推荐
- How to measure small current with oscilloscope and current probe
- 显示是否紧急
- Kotlin's extended function knowledge points
- SAP UI5 数据类型(data type) 学习笔记
- 多款无源探头1:1衰减比有什么区别
- 快速搭建属于你自己的WordPress博客站点【玩转华为云】
- 基于 Traefik 的激进 TLS 安全配置实践
- Dongfeng Nissan recalls some Xiaoke with potential safety hazards
- redis常见面试题有哪些?redis集群面试题及答案整理
- [in depth understanding of tcallusdb technology] example code - asynchronous call interface
猜你喜欢

建筑业未来的发展方向:数字化工厂管理系统

Tcallusdb Jun · industry news compilation (V)

Dongfeng Nissan recalls some Xiaoke with potential safety hazards

SAP UI5 应用开发教程之七十一 - SAP UI5 页面的嵌套路由

企业级知识管理(KM)建设方法及过程

How to measure small current with oscilloscope and current probe

Who will do the school's fixed asset management system? Yunna RFID fixed asset management system

【图】207. 课程表

【合泰HT32F52352定时器的使用】

Face recognition (4) face alignment
随机推荐
Sequential list -- basic implementation of one-way headless linked list
[in depth understanding of tcallusdb technology] example code for deleting data - [generic table]
Terraform 最佳实践:典型文件布局
Grafana系列文章-「译」基于 Grafana 的全栈可观察性 Demo
E. 2-Letter Strings
Computer Vision L7 -- Self-supervised Learning
07-有关函数的知识点
Ansible practical tips - batch patrol site URL status
使用HAL库、STM32CubeMX和Keil 5开发入门教程(一):点亮一盏LED灯(NUCLEO-F411RE)
[in depth understanding of tcallusdb technology] sample code of scanning data - [generic table]
【时序】DeepGLO:可以学习全局依赖和局部信息的多时间序列预测模型
ROS communication mechanism II - service communication
云呐|最新酒店行业固定资产管理办法,酒店实物资产管理系统
[in depth understanding of tcallusdb technology] sample code for reading the data of the specified location in the list - [list table]
顺序表——单向无头链表基础实现
ROS communication mechanism III - parameter server
vscode处理代码合并冲突
Transport layer UDP protocol
Vscode handles code merge conflicts
How to select current clamp or current probe