1. 程式人生 > 其它 >常用類-String的不可變性

常用類-String的不可變性

/**
* 1.String宣告為final的,不可被繼承
* 2.String實現了Serializable介面:表示字串是支援序列化的
* 實現了 Comparable介面:表示String可以比較大小
* 3.String內部定義了final char[] value用於儲存字串資料
* 4.String:代表不可變的字串序列,簡稱不可變性
* 體現:1)當對字串重新賦值時,需要重寫指定記憶體區域的,不能使用原有的value進行賦值。
* 2)當對現有的字串進行連線操作時,也需要重新指定記憶體區域賦值,不能使用原有的value進行賦值。
* 3)當呼叫String的replay()修改指定的字元或字串時,也需要重寫指定記憶體區域的,不能使用原有的value進行賦值。

* 5.通過字面量的方式(區別於new)給一個字串賦值,此時的字串值宣告在方法區中的字串常量池中。
* 6.字串常量池中是不會儲存相同內容的字串的
*
* 面試題: String s3 = new String("abc");方式建立物件,在記憶體中建立了幾個物件?
* 答:兩個,一個是堆空間中new結構,另一個是char[]對應的常量池中的資料:"abc"
*
* 7.String不同拼接操作的對比:
* 1)常量與常量的拼接結果在常量池。且常量池中不會存在相同內容的常量
* 2)只要其中有一個是變數,結果就在堆中
* 3)如果拼接的結果呼叫intern(),返回值就在常量池中

*
*
* @author fu jingchao
* @creat 2021/10/29-16:33
*/


 1 package com.atfu.java01;
 2 
 3 /**
 4  * @author fu jingchao
 5  * @creat 2021/10/29-16:33
 6  */
 7 public class StringTest {
 8     public static void main(String[] args) {
 9         String s1 = "abc";//通過字面量的方式給一個字串賦值,此時的字串值宣告在方法區中的字串常量池中。
10         String s2 = "abc";
11 String s3 = new String("abc"); 12 String s4 = new String("abc");//通過建立物件的方式給字串賦值,此時的s2儲存的地址值,是資料在堆 13 // 空間中開闢空間以後對應的地址值。 14 System.out.println(s1 == s2);//true 15 System.out.println(s1 == s3);//false 16 System.out.println(s1 == s4);//false 17 System.out.println(s3 == s4);//false 18 19 System.out.println("================================="); 20 Person p1 = new Person("Tom", 12); 21 Person p2 = new Person("Tom", 12); 22 System.out.println(p1.name.equals(p2.name));//true 23 System.out.println(p1.name == p2.name);//true 24 p1.name = "jack"; 25 System.out.println(p2.name);//Tom 26 27 System.out.println("******************************"); 28 //String不同拼接操作的對比 29 String s5 = "javaEE"; 30 String s6 = "hadoop"; 31 32 String s7 = "javaEEhadoop";//一個字面量 33 String s8 = "javaEE" +"hadoop";//兩個字面量的拼接,結果還是在常量池中,且由於內容和s7一樣,所以共用一個。 34 String s9 = s5+"hadoop";//只要其中有一個是變數,結果就在堆中 35 String s10 = "javaEE"+s6; 36 String s11 = s5+s6; 37 38 System.out.println(s7 ==s8 );//true 39 System.out.println(s7 ==s9 );//false 40 System.out.println(s7 ==s10 );//false 41 System.out.println(s7 ==s11 );//false 42 System.out.println(s9 ==s10 );//false 43 System.out.println(s9 ==s11 );//false 44 45 //如果拼接的結果呼叫intern(),返回值就在常量池中 46 String s12 = s9.intern();//返回得到的s12使用的是常量池中已經存在的 "javaEEhadoop" 47 System.out.println(s7 == s12);//true 48 49 50 } 51 52 } 53 54 class Person{ 55 String name; 56 int age; 57 58 public Person(String name, int age) { 59 this.name = name; 60 this.age = age; 61 } 62 63 public Person() { 64 } 65 66 }


此為本人學習筆記,若有錯誤,請不吝賜教