Object.equals和String.equals的區別詳解


前言

Java中的堆和常量池的區別是什么呢?Object.equals與String.equals的區別呢?下面讓我們通過一個小示例讓你明白它~

1、基礎知識

Java的存儲空間:寄存器、棧、堆、靜態存儲區、常量存儲區(常量池)、其他存儲位置。

此處重點介紹堆和常量存儲區:

堆:存儲new的對象;

常量池:用來存儲final static、String的常量。

2、Object.equals與String.equals的區別

Object.equals(==):比較內存地址;

String.equals: 比較內容即可,不管內存地址。

總結:

Object.equals相等,String.equals一定相等;

String.equals相等,Object.equals不一定相等。

3、實戰演練

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class TestString {
 public static void main(String[] args){
 // 維護在常量池里面
 String a="hello";
 String b="hello";
 // new出來的所有對象都在堆內存中
 // 只要是new出現來的都是新對象
 String c=new String("hello");
 String d=new String("hello");
 // 對比內存地址
 //true
 System.out.println(a==b);
 //false
 System.out.println(a==c);
 //false
 System.out.println(c==d);
 //對比內容
 //true
 System.out.println(a.equals(b));
 //true
 System.out.println(a.equals(c));
 //true
 System.out.println(c.equals(d));
 }
}

解釋:

a,b都是常量,a和b都是指向常量存儲區中的常量'hello',所以無論內容還是內存地址都是一樣的,因此a==b以及a.equals(b)都是true;

c,d都是變量,他們都是new出來的對象,里面存在兩個hello變量,c和d分別指向自己的hello變量,所以c和d內容一樣,但是內存地址不一樣,因此c==d是false,但是c.equals(d)為true。

 

 

to:https://www.cnblogs.com/zx-bob-123/p/8117958.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM