On the String intern

String existence stringtable

  1. All java classes share a string constant pool. A need for such a category of "hello" string constants, class B need the same string constant, the string they are acquired from the character string constant pool, and the address of the string constant is obtained is the same as obtained .
  2. In fact, in order to improve the matching speed, ie faster find out if a string exists in the constant pool, Java string constant pool in the design when using a stringtable table, inside it holds a reference to a string of similar in HashMap, we can find the corresponding entry in accordance with hashcode string, if there is a conflict, it may be a linked list entry, and then traverse the Java entry list, matching references corresponding string, if the find string, returns a reference, if you get less than a string, the string will put constant pool, and save a reference to stringtable years.

How can enter a string constant pool - ldc instruction is executed only strings will enter the string constant pool

Places where there are enclosed in double quotes will be used ldc instruction strings, such as String a = "hello".

The role of intern is to string out the new add a reference to the stringtable, java will first calculate the hashcode string look stringtable whether there has been a corresponding string references, if there is to return a reference (address), then no string stringtable into the address, and returns the string of reference (address).

  1. Because there is a string enclosed in double quotes, it will ldc command, that "test" we will be added to the string constant pool, its reference is the address of an array of char string, it will be added to our stringtable in. So a.intern when, in fact, return address of an array of char in the string, and the address of a string of examples is certainly not the same.
    public static void main(String[] args) {
        String a = new String("test");
        System.out.println(a.intern() == a);//false
    }
复制代码
  1. new String ( "jo") + new ( "hn") String will actually turn append stringbuffer then tosring () it is actually new a new string out. In this process, there is no double quotes john, that is to say does not perform ldc john then add a reference to the stringtable, the intern when the string is in fact the new address (i.e., address e) was added to stringtable and returns back.
String e = new String("jo") + new String("hn");
        System.out.println(e.intern() == e);//true
复制代码

Guess you like

Origin juejin.im/post/5d6a0675f265da03bb4abfbf