1
0
mirror of https://github.com/Snailclimb/JavaGuide synced 2025-06-16 18:10:13 +08:00

补充内容

This commit is contained in:
Snailclimb 2018-08-07 20:37:09 +08:00 committed by GitHub
parent deffbef084
commit 0708e12a97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -202,6 +202,33 @@ class Person {
- 情况2类覆盖了equals()方法。一般我们都覆盖equals()方法来两个对象的内容相等若它们的内容相等则返回true(即,认为这两个对象相等)。
**举个例子:**
```java
public class test1 {
public static void main(String[] args) {
String a = new String("ab"); // a 为一个引用
String b = new String("ab"); // b为另一个引用,对象的内容一样
String aa = "ab"; // 放在常量池中
String bb = "ab"; // 从常量池中查找
if (aa == bb) // true
System.out.println("aa==bb");
if (a == b) // false非同一对象
System.out.println("a==b");
if (a.equals(b)) // true
System.out.println("aEQb");
if (42 == 42.0) { // true
System.out.println("true");
}
}
}
```
**说明:**
- String中的equals方法是被重写过的因为object的equals方法是比较的对象的内存地址而String的equals方法比较的是对象的值。
- 当创建String类型的对象时虚拟机会在常量池中查找有没有已经存在的值和要创建的值相同的对象如果有就把它赋给当前引用。如果没有就在常量池中重新创建一个String对象。
## 三 hashCode与equals重要
面试官可能会问你:“你重写过 hashcode 和 equals 么为什么重写equals时必须重写hashCode方法