String相關使用

2021-09-02 19:17:42 字數 1712 閱讀 9290

偶然碰到乙個關於string物件呼叫intern()方法的問題,在此作一下回顧總結:

1、string是不可變物件,其底層維護乙個final型的字串陣列。

private final char value;
這也就是為什麼在需要進行大量的字串拼接的地方,都建議不要使用"+"拼接,每次都會重新重新構造乙個string物件

2、string中物件的比較,"=="和equals的使用:

"=="比較的是string物件的位址是否相同,而equals比較的是string物件的內容,即字串的內容是否一致。

string str1 = "hello";

string str2 = "hello";

system.out.println(str1 == str2);

結果為true.jvm中存在乙個字串常量池,在初始化str1的時候,"hello"會被存放到字串常量池中,然後在初始化str2的時候,

在常量池中找到"hello",str2也會指向這個"hello",所以str1和str2引用的同乙個字串物件。

string str1 = "hello";

string str2 = new string("hello");

system.out.println(str1 == str2);

結果為false,因為str2是重新new的物件,存放在堆上,所以str1和str2指向的是兩個不同的物件。

string str1 = "hello";

string str2 = new string("hello");

system.out.println(str1 == str2.intern());

intern()方法,string原始碼中解釋如下,當intern方法被呼叫時,會首先去字串常量池中去查詢是否包含與之相同字串內容的

物件,如果存在則會返回此物件,反之則會把此物件加入到string pool中

* * when the intern method is invoked, if the pool already contains a

* string equal to this object as determined by

* the method, then the string from the pool is

* returned. otherwise, this object is added to the

* pool and a reference to this object is returned.

*

上例子中,初始化str1時候,"hello"被加入到string pool中,str2呼叫intern方法,在string pool中查詢到"hello",然後返回此物件,str1和str2都指向同乙個物件,所以結果返回true;

string str1 = new string("hello");

system.out.println(str1 == str1.intern());

在初始化構造str1的時候,使用new在堆上建立乙個物件。str1指向堆上的乙個物件,而引數"hello"作為字串常量被加入到string pool中,所以在str1呼叫intern的時候,在常量池查詢到"hello"並返回,最後列印false。

string 的相關用法

編寫類string的建構函式 析構函式和賦值函式 25分 已知類string的原型為 class string 請編寫string的上述4個函式。標準答案 string的析構函式 string string void 3分 string的普通建構函式 string string const char...

String相關的知識

1 string stringbuffer與stringbuilder的區別 string 字串常量,長度不可變 stringbuffer 字串變數,長度可變,執行緒安全 stringbuilder 字串變數,長度可變,非執行緒安全。2 stringutils.isblank和stringutils...

String相關的方法

charat 0 獲取字元 tochararray 獲取對應的字元陣列 substring 擷取子字串 split 根據分隔符進行分割 string sentence 蓋倫,在進行了連續8次擊殺後,獲得了 超神 的稱號 根據,進行分割,得到3個子字串 string subsentences sent...