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

查看:37
本文介绍了字符串是 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?

推荐答案

除了已经说过的,String literals [ie, Strings like "abcd" 但是不像 Java 中的 new String("abcd")] 被实习 - 这意味着每次你引用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天全站免登陆