-5

如何将堆区数据移动到字符串常量池?

        String s3 = new String("Test");
         final String s4 = s3.intern();
         System.out.println(s3 == s4);//fasle(i need true)

我不想创建新对象,所以只需从堆中剪切对象并将其粘贴到字符串常量池中

4

1 回答 1

0

当您调用时,您不会将堆数据移动到字符串常量池intern,如果常量池中尚不存在另一个新字符串,您只是将另一个新字符串添加到常量池中(在您的情况下不会发生,因为"Test"已经添加到第-1行的常量池)。

您可能希望将代码更改为:

public static void main(String[] args) {
    String s3 = new String("Test");
    s3 = s3.intern();
    String s4 = "Test";
    System.out.println(s3 == s4);//fasle(i need true)
}

在上面的代码中,您再次将 s3 的实习值的引用分配给 s3。接下来,您从 S4 中的字符串常量池中获取相同的对象。

于 2016-09-30T05:40:35.397 回答