首页 > 代码库 > java的equal和==问题

java的equal和==问题

看一本比较简略的java教程,在看到对象的时候,书上直接给我来一句:

                  

刚看下觉得没什么问题,很有道理的一个东东嘛,但是出于习惯还是打了几行代码测试了一下,代码如下:

 

 1 class Person { 2     private String name; 3     private int age; 4     private double gread; 5  6     public Person(String name, int age, double gread) { 7         this.name  = name; 8         this.age = age; 9         this.gread = gread;10     }11     public String talk() {12         return "Name: " + this.name + "\n" +13                "Age: " + this.age + "\n" +14                "Gread: " + this.gread;15     }16 }17 18 public class AnonymousObject {19     public static void main(String[] args) {20         Person per1 = new Person("wc", 21, 99);21         Person per2 = new Person("wc", 21, 99);22         Person per3 = new Person("wd", 21, 99);23         System.out.println("per1 == per2: " + (per1 == per2));24         System.out.println("per1.equals(per2): " + (per1.equals(per2)));25         System.out.println("per1 == per3: " + (per1 == per3));26         System.out.println("per1.equals(per3): " + (per1.equals(per3)));27     }28 }

预期来看,24行的结果应该是true才对,但是运行结果是:

                

然后我就很蛋碎的区找原因,然后发现 equals 的定义原来是这样的:

1  public boolean equals(Object obj) {2     return (this == obj);3     }

也就是说, equals 实质上是和 == 一样的,比较的其实都是引用,而 String 对象用 equals 比较时只要内容相同结果就为 true 的原因是 String 重写了 equals,代码如下:

 1 public boolean equals(Object anObject) { 2     if (this == anObject) { 3         return true; 4     } 5     if (anObject instanceof String) { 6         String anotherString = (String)anObject; 7         int n = count; 8         if (n == anotherString.count) { 9         char v1[] = value;10         char v2[] = anotherString.value;11         int i = offset;12         int j = anotherString.offset;13         while (n-- != 0) {14             if (v1[i++] != v2[j++])15             return false;16         }17         return true;18         }19     }20     return false;21     }

所以,在我们自己实现的类里面来说,equals 和 == 是完全等效的,除非我们也重写 equals。

但是,如果不重写 equals,那 equals 就完全失去它的作用了,所以我们一般都会重写这个函数使它变成比较两个对象的内容是否相等。