正在创建多少个对象?

编程入门 行业动态 更新时间:2024-10-16 02:24:18
本文介绍了正在创建多少个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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(); } }

更多推荐

正在创建多少个对象?

本文发布于:2023-11-25 04:44:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多少个   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!