字符串是Java中的对象,那么为什么我们不使用“new”来创建它们呢? [英] Strings are objects in Java, so why don't we use 'new' to create them?

查看:531
本文介绍了字符串是Java中的对象,那么为什么我们不使用“new”来创建它们呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通常使用 new 关键字创建对象,例如:

We normally create objects using the new keyword, like:

Object obj = new Object();

字符串是对象,但我们不使用 new 创建它们:

Strings are objects, yet we do not use new to create them:

String str = "Hello World";

这是为什么?我可以用 new 制作一个字符串吗?

Why is this? Can I make a String with new?

推荐答案

除了什么已经说过,字符串文字 [即字符串如abcd但不像新字符串(abcd)在Java中实现] - 这意味着每次引用abcd时,都会获得对单个 String 实例的引用,而不是每次一个新的。所以你将拥有:

In addition to what was already said, String literals [ie, Strings like "abcd" but not like new String("abcd")] in Java are interned - this means that every time you refer to "abcd", you get a reference to a single String instance, rather than a new one each time. So you will have:

String a = "abcd";
String b = "abcd";

a == b; //True

但如果你有

String a = new String("abcd");
String b = new String("abcd");

然后可以

a == b; // False

(如果有人需要提醒,请始终使用 .equals ()比较字符串; == 测试物理相等性。)

(and in case anyone needs reminding, always use .equals() to compare Strings; == tests for physical equality).

实习字符串文字是好的,因为它们经常被使用多次。例如,考虑(设计的)代码:

Interning String literals is good because they are often used more than once. For example, consider the (contrived) code:

for (int i = 0; i < 10; i++) {
  System.out.println("Next iteration");
}

如果我们没有字符串实习,则需要下一次迭代要实例化10次,而现在它只会被实例化一次。

If we didn't have interning of Strings, "Next iteration" would need to be instantiated 10 times, whereas now it will only be instantiated once.

这篇关于字符串是Java中的对象,那么为什么我们不使用“new”来创建它们呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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