如何知道将使用以下代码创建多少个对象? [英] How to know how many objects will be created with the following code?

查看:91
本文介绍了如何知道将使用以下代码创建多少个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Strings,我对于对象的情况有点困惑,所以想知道将使用以下代码创建多少个对象,并对String对象和堆创建String对象进行一些解释。

I am bit confused in case of objects when it comes to Strings, So wanted to know how many objects will be created with following code, with some explanation about String objects creation with respect to String pool and heap.

 public static void main(String[] args) {

    String str1 = "String1";

    String str2 = new String("String1");

    String str3 = "String3";

    String str4 = str2 + str3;

    }


推荐答案

4个对象将被创建。

两个音符:


  • new String(something)总是创建一个新对象。字符串文字something仅为所有匹配项创建一个对象。最好的做法是永远不要使用 new String(something) - 实例化是多余的。

  • 两个字符串的串联是转换为 StringBuilder.append(第一个).append(第二个).toString(),这样就创建了另一个对象。

  • new String("something") always creates a new object. The string literal "something" creates only one object for all occurrences. The best practice is to never use new String("something") - the instantiation is redundant.
  • the concatenation of two strings is transformed to StringBuilder.append(first).append(second).toString(), so another object is created here.

这篇关于如何知道将使用以下代码创建多少个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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