mu_tou_man

导航

 

 

 A."=="可用于基本类型和引用类型:

  当用于基本类型时候,是比较值是否相同;1==2; false;

  当用于引用类型的时候,是比较是否指向同一个对象。

 B.基本类型int、char、float等没有equals方法,equals只比较值(对象中的内容)是否相同(相同返回true)。

 C.一般的类,当没有重写equals方法时,equals()方法与“==”作用是相同的;

 D.对于String类较为特殊:

          String a = "abc"; String b="abc"; a==b 返回true,a.equals(b)返回true, 因为abc放在data区域;

      String a = new String("hello"); String b=new String("hello"); a==b是false(指向不同对象), 而a.equals(b)返回true(对象内容相同);

E .更一般的,当equals()被重写时,往往用于对象的内容是否相同,请看下面的例子:

 1 public class TestEqual{
 2     public static void main(String[] args)
 3     {
 4         Cat c1 = new Cat(1, 2, 3);
 5         Cat c2 = new Cat(1, 2, 3);
 6         Cat c3 = new Cat(2, 2, 2);
 7         System.out.println(c1 == c2);//返回false 不指向同一个对象
 8         System.out.println(c1.equals(c2));//返回true 对象内容相同
 9         System.out.println(c1 == c3);//返回false 不指向同一个对象
10         System.out.println(c1.equals(c3));//返回false 对象内容不同
11     }
12 }
13 
14 class Cat 
15 {
16     int color;
17     int height, weight;
18     
19     public Cat(int color, int height, int weight) 
20     {
21         this.color = color;
22         this.height = height;
23         this.weight = weight;
24     }
25     
26     public boolean equals(Object obj) 
27     {
28         if(obj == null) return false;
29         else{
30                 if(obj instanceof Cat)
31                 {
32                     Cat c = (Cat)obj;
33                     if(c.color == this.color && c.height == this.height && c.weight == this.weight)
34                     {
35                         return true;
36                     }
37                 }
38             }
39         return false;
40     }
41     
42 }

 

 

posted on 2014-06-17 15:21  mu_tou_man  阅读(305)  评论(0编辑  收藏  举报