字符串初始化差异 [英] String initialization difference

查看:99
本文介绍了字符串初始化差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先道歉,如果这是一个非常基本的问题,我很想知道以下字符串定义之间的区别

Firstly apologies if this a very basic question, I'm just curious to know the difference between the following string definitions

String x= "hello";
String y = new String("hello");

我知道在Java中String是一个类,它既不是基元也不是包装器(如果这是一个错误的观念,请纠正我).考虑一个A类,到目前为止,对于任何一个类,我都看过以下声明.我认为A c;是有效的,而A a = new A();也是有效的.我对A a ="xyz";感到困惑,这就是我们在上述第一种定义类型中声明String的方式.我确定上面的两个定义是绝对不同的,就像我说x==y一样,它返回false.我知道y是对String对象的引用. x在那里是什么,它如何存储在内存中,有趣的是,我发现x和y都可以访问String类的所有方法.

I knew that in java String is a Class its neither a primitive nor a Wrapper(Correct me if this a misconception). Consider a class A, I've seen the following declarations for any class so far. i think A c; is valid and A a = new A(); is also valid. I'm confused with A a ="xyz"; this is how we declared a String as in above first type of definition. I'm sure that the above two definitions are absolutely different, like if i say x==y it returns false. I understand that y is the reference to the String object. What is x there, how is it stored in memory, interestingly i found that both x and y can access all the methods of String class.

那么一个人相对于另一个人有什么优势.我能知道每个人的适用性吗?

Then what is the advantage of one over other.Can i know the applicability of each.

推荐答案

摘自约书亚·布洛赫(Joshua Bloch)第二版有效的Java":

From the 2nd edition of Joshua Bloch's "Effective Java":

String s = new String("stringette");// DON'T DO THIS!

该语句每次执行时都会创建一个新的String实例, 这些对象的创建都不是必需的.的论点 字符串构造函数("stringette")本身是一个String实例, 在功能上与由 构造函数.如果此用法发生在循环中或频繁调用中 方法,可以不必要地创建数百万个String实例.这 改进的版本如下:

The statement creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor ("stringette") is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:

String s = "stringette";

这篇关于字符串初始化差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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