equals和“==”

Integer a = new Integer("3");
Integer b = new Integer(3);
System.out.println(a==b);
System.out.println(a.equals(b));

在堆内存中new了两个不同的对象,可以将这两个对象看做是两个空间,两个空间有两个不同的地址值标记。

a、b中记录的就是这两个地址值;“==”比较的就是地址值,所以“a==b”不成立。

a和b叫做引用变量,是Integer类型的。。

要比较两个对象是否相等,必须通过比较这两个对象内容(属性)是不是相等的;这就要用到从Object中继承的equals方法。

 

当用到equals方法时,分两种情况:一是比较的对象是API中已经定义的类的类型;二是API中没有,二是自己定义的,比如定义猫、狗等类。

当是第一种情况,可以直接比较两个对象的内容是否相等;当是第二种情况,需要自己重写从Object继承下来的equals方法,例如自定义的猫类,必须在equals定义两个猫(对象)相等的条件,例如身高,体重相等,就说这两个猫(对象)是相等的。。。。

 

如果想具体的了解equals和“==”的应用,可以访问链接http://www.jb51.net/article/73949.htm

 

以下程序:

 1 public class Test {
 2 
 3     public static void main(String[] args) {
 4         String s = "hello";
 5         String t = "hello";
 6         char c[] = {'h','e','l','l','o'};
 7         if(s.equals(t))
 8             System.out.println("1true");
 9         else
10             System.out.println("1false");
11         if(s.equals(c))
12             System.out.println("2true");
13         else
14             System.out.println("2false");
15         
16         if(s.equals(new String("hello")))
17             System.out.println("3true");
18         else
19             System.out.println("3false");
20         
21         if(s == t)
22             System.out.println("4true");
23         else
24             System.out.println("4false");
25     }
26 
27 }

输出结果为:

1true
2false
3true
4true

 

 1 public class Test3 {
 2 
 3     public static void main(String[] args) {
 4         String s = "hello";
 5         String t = "hello";
 6         String str = "hello";
 7         char c[] = {'h','e','l','l','o'};
 8         
 9         char ch[] = str.toCharArray();
10         
11         if(ch == c)
12             System.out.println("1true");
13         else
14             System.out.println("1false");
15         if(ch.equals(c))
16             System.out.println("2true");
17         else
18             System.out.println("2false");
19         
20         String s2 = new String(c);
21 
22         if(s2 == (s))
23             System.out.println("3true");
24         else
25             System.out.println("3false");
26         
27         if(s2.equals(s))
28             System.out.println("4true");
29         else
30             System.out.println("4false");
31     }
32 
33 }

输出结果为:

1false
2false
3false
4true

 

 1 public class Test3 {
 2 
 3     public static void main(String[] args) {
 4         String s = "hello";
 5         String t = "hello";
 6         if(s == t)
 7             System.out.println("5true");
 8         else
 9             System.out.println("5false");
10     }
11 }

输出结果为:

5true

posted @ 2016-11-21 17:37  XuGuobao  阅读(328)  评论(0编辑  收藏  举报