简体   繁体   English

String.intern()如何工作以及它如何影响String池?

[英]How does String.intern() work and how does it affect the String pool?

As we know, String().intern() method add String value in string pool if it's not already exist. 我们知道, String().intern()方法在字符串池中添加String值(如果它尚不存在)。 If exists, it returns the reference of that value/object. 如果存在,则返回该值/对象的引用。

String str = "Cat"; // creates new object in string pool  with same character sequence.  
String st1 = "Cat"; // has same reference of object in pool, just created in case of 'str'

 str == str1 //that's returns true

String test = new String("dog");
test.intern();// what this line of code do behind the scene

I need to know, when i call test.intern() what this intern method will do? 我需要知道,当我调用test.intern()这个实习方法会做什么?

add "dog" with different reference in string pool or add test object reference in string pool(i think, it's not the case )? 在字符串池中添加带有不同引用的“dog”或在字符串池中添加test对象引用(我认为,情况并非如此)?

I tried this 我试过这个

String test1 = "dog";

test == test1 // returns false

I just want to make sure, when I call test.intern() it creates new object with same value in String pool? 我只是想确保,当我调用test.intern()它会在String池中创建具有相同值的新对象? now I have 2 objects with value "dog". 现在我有两个值为“dog”的对象。 one exist directly in heap and other is in String pool? 一个直接存在于堆中,另一个存在于String池中?

when i call test.intern() what this intern method will do? 当我调用test.intern()这个实习方法会做什么?

It will put the "dog" string in the string pool (unless it's already there). 它会将"dog"字符串放在字符串池中(除非它已经存在)。 But it will not necessarily put the object that test refers to in the pool. 但它不一定会将test所指的对象放在池中。 This is why you typically do 这就是你通常这样做的原因

test = test.intern();

Note that if you have a "dog" literal in your code, then there will already be a "dog" in the string pool, so test.intern() will return that object. 请注意,如果您的代码中有"dog"字面值,那么字符串池中已经存在"dog" ,因此test.intern()将返回该对象。

Perhaps your experiment confuses you, and it was in fact the following experiment you had in mind: 也许你的实验让你困惑,实际上你想到的是以下实验:

String s1 = "dog";             // "dog" object from string pool
String s2 = new String("dog"); // new "dog" object on heap

System.out.println(s1 == s2);  // false

s2 = s2.intern();              // intern() returns the object from string pool

System.out.println(s1 == s2);  // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM