mirror of
https://github.com/Snailclimb/JavaGuide
synced 2025-06-16 18:10:13 +08:00
补充内容
This commit is contained in:
parent
deffbef084
commit
0708e12a97
@ -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方法?”
|
||||
|
Loading…
x
Reference in New Issue
Block a user