java.lang.string方法intern()

java.lang.string https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--

intern

public String intern()

返回字符串对象的规范表示。
Returns a canonical representation for the string object.

String 类私有维护一个字符串池,初始为空。
A pool of strings, initially empty, is maintained privately by the class String.

调用 intern 方法时,如果池中已包含一个通过 equals(Object) 方法确定与此 String 对象相等的字符串,则返回池中的字符串。否则,将此 String 对象添加到池中,并返回对此 String 对象的引用。
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

因此,对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为真时,s.intern() == t.intern() 才为真。
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

所有字符串字面量和字符串值常量表达式均会被 intern。字符串字面量定义在 Java™ 语言规范的 3.10.5 节中。
All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

Returns:
一个与此字符串内容相同的字符串,但保证来自唯一字符串池。
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

posted @ 2025-04-15 15:35  kuki'  阅读(26)  评论(0)    收藏  举报