File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -202,6 +202,33 @@ class Person {
202202- 情况2:类覆盖了equals()方法。一般,我们都覆盖equals()方法来两个对象的内容相等;若它们的内容相等,则返回true(即,认为这两个对象相等)。
203203
204204
205+ ** 举个例子:**
206+
207+ ``` java
208+ public class test1 {
209+ public static void main (String [] args ) {
210+ String a = new String (" ab" ); // a 为一个引用
211+ String b = new String (" ab" ); // b为另一个引用,对象的内容一样
212+ String aa = " ab" ; // 放在常量池中
213+ String bb = " ab" ; // 从常量池中查找
214+ if (aa == bb) // true
215+ System . out. println(" aa==bb" );
216+ if (a == b) // false,非同一对象
217+ System . out. println(" a==b" );
218+ if (a. equals(b)) // true
219+ System . out. println(" aEQb" );
220+ if (42 == 42.0 ) { // true
221+ System . out. println(" true" );
222+ }
223+ }
224+ }
225+ ```
226+
227+ ** 说明:**
228+ - String中的equals方法是被重写过的,因为object的equals方法是比较的对象的内存地址,而String的equals方法比较的是对象的值。
229+ - 当创建String类型的对象时,虚拟机会在常量池中查找有没有已经存在的值和要创建的值相同的对象,如果有就把它赋给当前引用。如果没有就在常量池中重新创建一个String对象。
230+
231+
205232## 三 hashCode与equals(重要)
206233
207234面试官可能会问你:“你重写过 hashcode 和 equals 么,为什么重写equals时必须重写hashCode方法?”
You can’t perform that action at this time.
0 commit comments