How String Literal Pool Works

前端 未结 2 721
不思量自难忘°
不思量自难忘° 2020-12-03 13:26
String str = new String(\"Hello\");

Normally I have read, in many articles available on internet, that two objects are created when we write the st

相关标签:
2条回答
  • 2020-12-03 13:44

    If I understand your question correctly, you're asking how to initialize a string without placing it in the string literal pool. You can avoid this as long as you don't declare a string literal expression (don't declare a series of characters in double quotes.)

    // these two strings will be placed in the string literal pool
    String one = "one";             
    String two = new String("two");
    // this third string will NOT be placed in the string literal pool
    String three = new String(new char[] {'t', 'h', 'r', 'e', 'e'});
    
    0 讨论(0)
  • 2020-12-03 13:49

    There's only ever be one string with the contents "Hello" in the literal pool. Any code which uses a string constant with the value "Hello" will share a reference to that object. So normally your statement would create one new String object each time it executed. That String constructor will (IIRC) create a copy of the underlying data from the string reference passed into it, so actually by the time the constructor has completed, the two objects will have no references in common. (That's an implementation detail, admittedly. It makes sense when the string reference you pass in is a view onto a larger char[] - one reason for calling this constructor is to avoid hanging onto a large char[] unnecessarily.)

    The string pool is used to reduce the number of objects created due to constant string expressions in code. For example:

    String a = "Hello";
    String b = "He" + "llo";
    String c = new String(a);
    
    boolean ab = a == b; // Guaranteed to be true
    boolean ac = a == c; // Guaranteed to be false
    

    So a and b refer to the same string object (from the pool) but c refers to a different object.

    0 讨论(0)
提交回复
热议问题