码迷,mamicode.com
首页 > 其他好文 > 详细

==、!=和equals区别

时间:2021-05-24 16:12:34      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:布尔   bool   bsp   tput   font   system   integer   ati   head   

Java— ==、!=和equals区别

1、==和!=

==和!=适用于所有对象,==表示是否相等,!=表示是否不相等,结果都为布尔值,true或false。

 

 1 public class test {
 2     public static void main(String[] args) {
 3         Integer n1 = new Integer(47);
 4         Integer n2 = new Integer(47);
 5         System.out.println(n1==n2);
 6         System.out.println(n1!=n2);
 7     }
 8 }
 9 ?
10 /**
11  *Output:
12  * false
13  * true
14  * */

 

n1和n2的内容都是47,但n1和n2是两个对象的引用。由于==和!=比较的是对象的引用,因而出现以上的结果。

基本类型可以通过==和!=进行比较,如下代码所示。

 

 1 public class test1 {
 2     public static void main(String[] args) {
 3         int n1 = 6;
 4         int n2 = 6;
 5         System.out.println(n1==n2);
 6         System.out.println(n1!=n2);
 7     }
 8 }
 9 ?
10 /**
11  *Output:
12  * true
13  * false
14  * */

 

2、equals

比较两个对象的实际内容是否相同通过equals实现,但这个方法不适用于基本类型。

 

 1 public class test {
 2     public static void main(String[] args) {
 3         Integer n1 = new Integer(47);
 4         Integer n2 = new Integer(47);
 5         System.out.println(n1.equals(n2));
 6     }
 7 }
 8 ?
 9 /**
10  *Output:
11  * true
12  * */

 

3、自定义类使用equals

在自定义类中,equals()的默认行为是比较引用,所以如果需要比较对象的实际内容,在自定义类中需要覆盖equals方法。

 

 1 public class test {
 2     public static void main(String[] args) {
 3         Value1 v1=new Value1();
 4         v1.i=6;
 5         Value1 v2=new Value1();
 6         v2.i=6;
 7         System.out.println(v1.equals(v2));
 8 ?
 9         Value2 v3=new Value2();
10         v3.j=3;
11         Value2 v4=new Value2();
12         v4.j=3;
13         System.out.println(v3.equals(v4));
14     }
15 }
16 ?
17 class Value1{
18     int i;
19 }
20 ?
21 class Value2{
22     int j;
23 ?
24     public boolean equals(Value2 v) {
25         return j==v.j;
26     }
27 }
28 ?
29 /**
30  *Output:
31  * false
32  * true
33  * */

 


 

 

==、!=和equals区别

标签:布尔   bool   bsp   tput   font   system   integer   ati   head   

原文地址:https://www.cnblogs.com/yqsumAll/p/14784723.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!