在Java中有一个关于Stringz实例池的简单问题
Had a simple question around Stringz instance pooling in Java
如果我遇到这样的情况:场景1:
If I have a situation like this: Scenario 1:
String s1 = "aaa"; String s2 = new String("aaa");然后翻转场景2:
and then flipped Scenario 2:
String s1 = new String("aaa"); String s2 = "aaa";在每种情况下 - 字符串池和堆中创建了多少个对象? 我假设两者都会创建相同数量的对象(2个对象 - 字符串池中每个场景中的两个行都有一个单独的aaa,而新运算符则是一个)。 我在iview中被告知这不正确 - 我很好奇我的理解有什么问题?
In each case- how many objects are being created in the String Pool and Heap ? I assumed both would create an equal number of objects (2 Objects - one single "aaa" for both lines in each scenario in the String pool and one for the new Operator). I was told in an iview that this wasn't correct - I'm curious as to what is wrong with my understanding?
推荐答案文本aaa的字符串在加载类时创建并汇集,因此当你的两行时只创建一个新的String
The String for the literal "aaa" is created and pooled when the class is loaded, so only one new String is created when your two lines are the code is executed.
要清楚:这两个示例在执行时只创建一个新的String对象。文字是在第一次使用包含字符串aaa的类时创建的。
To be clear: both examples only create one new String object when they execute. The literal is created the first time a class containing the String "aaa" is used.
class FooBar{ void foo(){ String s1 = "aaa";//the literal already exists String s2 = new String("aaa");//creates string for s2 } void bar(){ String s1 = new String("aaa"); //creates string for s1 String s2 = "aaa";//the literal already exists } } class Test{ public void main(String... args){ ... //first time class FooBar used in program, class with literals loaded FooBar fb = new FooBar(); //creates one string object, the literal is already loaded fb.bar(); //also creates one string object, the literal is already loaded fb.foo(); } }更多推荐
正在创建多少个对象?
发布评论