我了解 java 中 intern() 的内部工作原理。它将开始引用字符串池区域对象。但是当我们将 inter() 与 new 一起使用时,它是否仍然在堆中创建一个对象并且引用现在指向池对象?或者它根本不会创建任何堆对象?
String s1 = new String("hello").intern();
比如上一行,当使用intern时,是不是只在字符串池中创建一个对象并引用它?或者它是在堆中创建一个对象,在池中创建一个对象,然后它开始引用池对象,从而将对象留在堆中以进行垃圾回收?
在 Oracle/OpenJDK 中,它不创建任何对象,但是,这是依赖于实现的。
intern()
方法要么返回现有对象,在本例中为原始“Hi”,要么返回用于调用 intern
的字符串
But when we use inter() along with new, does it still create an object in heap and the reference is now pointing to pool object?
字符串文字仍在堆中。没有任何东西被移动以将它添加到这个池中
For example in the above line, when intern is used, is it creating only one object in the string pool and referring it?
这只是创建一个对象,包装原始字符串文字的 char[]
或 byte[]
。 intern
将返回原始字符串文字。
Or is it creating one object in heap and one object in pool and it starts referring to pool object, thereby leaving the object at heap for garbage collection?
字符串文字池是在 native 内存中实现的,不是由对象组成的。
为了进行比较,调用 intern() 会将新字符串添加到文字池中,因为 concat
是在运行时计算的。
String hi = "h".concat("i").intern();
这什么都不做,因为 +
是在编译时计算的。
String hi = ("h" + "i").intern();