[英]Java - String & constant pool
我在java.lang.String
看到以下成員:
private final char value[];
我的問題是 :
下面的語句將文字字符串的副本復制到上面提到的char[]
,而常量池中也存在文字字符串的另一個副本。
String b1 = new String("abc");
如果是這樣,常量池的含義不是更小了嗎? 還是我們應該避免使用new()創建帶有文字的String?
@Update :
因此,根據答案,為什么String
類在其中需要一個char value[]
變量,為什么不只在常量池中引用單個副本呢? 如果使用new String("...")
創建一個字符串,如果池中尚不存在該文字,該文字是否不會放入常量池中?
根據我的想象,使用new String()
的唯一好處是,它可能比查詢常量池更快。 還是常量池有大小限制,如果大小不夠,它將刪除舊的常量值? 但是我不確定這是它的工作方式。
結論
因此,根據答案, new String()
僅應由常量池維護者本身使用,而我們程序員則不應。
沒錯。 使用new()
從文字中創建String
實例是絕對沒有意義的。
您可以使用new,但是使用String的“ intern”方法指定它會有些棘手。 像這樣:
String a = "ABC";
String b = new String("ABC").intern();
System.out.println(a == b);
輸出為true,如果沒有“ intern”,則它是來自常量池的副本。
String a = "ABC";
String b = new String("ABC");
System.out.println(a == b);
輸出為假。 如果查看此String構造函數的原型,它將顯示:
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
Java中的字符串類似於任何其他編程語言,都是字符序列。 這更像是用於該char序列的實用程序類。 此char序列在以下變量中維護:
/** The value is used for character storage. */
private final char value[];
當您使用這樣的new
關鍵字創建String時
String b1 = new String("abc");
然后將對象創建到Heap Memory
,當Java Compiler
遇到任何String文字時,它將在常量池中創建一個Object
現在b1指向堆內存中的對象,並且由於還存在字符串文字,因此還在常量池中創建了一個沒人指向的對象
如有效的Java 2nd Edition所述
String s = new String("neerajjain"); //DON'T DO THIS!
因為當只能由1個Object完成工作時,您不必要創建2個對象。
但在某些情況下,您可能會使用new String("string")
您可以在此處找到它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.