Java-equals和“==”的区别

区别:

  “==” 是比较运算符,可以用于判断基本数据类型是否相等,当用于判断引用类型的时候,比较的对象的内存地址是否相同

  equals是Object类当中的方法,不可以用于判断基本数据是否相等,可以用于判断引用类型是否相等,但是子类通常会重写该方法,比较对象的属性值是否相等,比如  ( String,Integer)

 

举例说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<code-pre class="code-pre" id="pre-h6jDXC"><code-line class="line-numbers-rows"></code-line>public class Test {
<code-line class="line-numbers-rows"></code-line>    public static void main(String[] args) {
<code-line class="line-numbers-rows"></code-line>        int num1 = 10;
<code-line class="line-numbers-rows"></code-line>        int num2 = 10;
<code-line class="line-numbers-rows"></code-line>        System.out.println(num1 == num2);   //true
<code-line class="line-numbers-rows"></code-line>        String str1 = "hello";
<code-line class="line-numbers-rows"></code-line>        String str2 = "hello";
<code-line class="line-numbers-rows"></code-line>        System.out.println(str1 == str1); //true
<code-line class="line-numbers-rows"></code-line>        String str3 = new String("hello");
<code-line class="line-numbers-rows"></code-line>        String str4 =  new String("hello");;
<code-line class="line-numbers-rows"></code-line>        System.out.println(str3 == str4); //false
<code-line class="line-numbers-rows"></code-line>        System.out.println(str3.equals(str4)); //true
<code-line class="line-numbers-rows"></code-line>    }
<code-line class="line-numbers-rows"></code-line>}
</code-pre>

   运行结果说明:因为在常量池中,一个常量只会对应一个地址,因此不管是再多的 "abc", 这样的数据都只会存储一个地址. 所以所有他们的引用都是指向的同一块地址,因此基本数据类型和String常量是可以直接通过==来直接比较的。

  第一个:true,"=="可以用于基本数据类型的比较

  第二个:true,str1和str2都是存储了“hello”,而“hello”存在于字符串常量池当中,str1和str2指向的都是字符串常量池中同一个地址

  第三个:false,当使用new操作符的时候,在内存当中开辟空间,此时的str3和str4指向的是不同的内存空间地址

  第四个:true,String类型重写了equals方法,比较的是str3和str4中存储的值

 


__EOF__

本文作者通过程序看世界
本文链接https://www.cnblogs.com/dbcxy/p/16846428.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   通过程序看世界  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示