String intern() behaviour

前端 未结 4 893
借酒劲吻你
借酒劲吻你 2020-12-11 11:27

From the javaDocs of String class\'s intern method :

When the intern method is invoked, if the pool already contains a string equal to this String o

4条回答
  •  粉色の甜心
    2020-12-11 12:01

    Because when you use the new String() syntax, you are not taking advantage of the String pool, but creating a new instance of String regardless of whether it is in the pool or not.

    Moral of the story.. NEVER use new String()

    You are at the mercy of the JVM, which has the choice of making the decision of whether or not an 'internalized' String already exists, or should be internalized. More specifically:

    To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.

    If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String. Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.

提交回复
热议问题