当我们使用new运算符在字符串常量池中精确创建对象时. [英] When exactly the object is created in string constant pool when we use new operator.?

查看:57
本文介绍了当我们使用new运算符在字符串常量池中精确创建对象时.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String s = new String("hello"); 

这里将创建两个对象,一个在堆内存中,另一个在字符串池中.

Here two objects will be created, one in heap memory and another in the string pool.

那么, intern()方法有什么用?上面的语句执行后,字符串"hello" 将在堆中以及字符串池中可用

So, what is the use of the intern() method? The string "hello" will be available in heap as well as the string pool after above statement execution

推荐答案

首先. String s = new String("hello"); 创建不必要的String,因此不应使用.接下来,调用 s = s.intern()将确保返回添加到SCP的"hello",因此在堆上创建的第二个字符串将有资格使用GC.

First of all. String s = new String("hello"); creates an unnecessary String and should not be used. Next, calling s = s.intern() will ensure that the "hello" added to SCP will be returned and hence the second string that was created on the heap will be eligible for GC.

intern()将字符串添加到SCP(如果尚不存在).通常,当您知道一个字符串被多次使用但不能使用 literal 创建它时,通常使用它.因此,您可以创建 intern 并确保只在SCP中放置一个字符串,并在1000个地方使用它(而不是同时创建数千个具有相同值的字符串,它们同时存在).堆上具有相同值的其他字符串也有资格使用GC)

intern() adds the string to the SCP if it is not already present. It is usually used when you know that a String is used multiple times but you cannot create it using literal. So instead of creating thousands of Strings with the same value, you (which exist simultaneously), you could use intern and ensure that only one String is put in the SCP and is used in 1000 places (and all other strings with the same value on the heap are eligible for GC)

这篇关于当我们使用new运算符在字符串常量池中精确创建对象时.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆