问题描述
我是一个学习 Java 的 C++ 人.我正在阅读 Effective Java,有些东西让我感到困惑.它说永远不要写这样的代码:
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:
String s = new String("silly");
因为它创建了不必要的 String
对象.但是应该这样写:
Because it creates unnecessary String
objects. But instead it should be written like this:
String s = "No longer silly";
到目前为止还好......但是,鉴于这个类:
Ok fine so far...However, given this class:
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null) {
throw new NullPointerException();
}
this.s = s;
}
:
:
}
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
String s = "polish";
为什么第一个语句没问题?不应该是
Why is the first statement ok? Shouldn't it be
CaseInsensitiveString cis = "Polish";
我如何让 CaseInsensitiveString
表现得像 String
那样才能使上述语句正常(有和没有扩展 String
)?String 是什么让它可以像这样传递一个文字?根据我的理解,Java 中没有复制构造函数"的概念?
How do I make CaseInsensitiveString
behave like String
so the above statement is OK (with and without extending String
)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
推荐答案
String
是该语言的特殊内置类.它适用于 String
类仅,您应该避免在其中说
String
is a special built-in class of the language. It is for the String
class only in which you should avoid saying
String s = new String("Polish");
因为文字 "Polish"
已经是 String
类型,并且您正在创建一个额外的不必要的对象.对于任何其他类,说
Because the literal "Polish"
is already of type String
, and you're creating an extra unnecessary object. For any other class, saying
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
是正确的(在这种情况下也是唯一的)做法.
is the correct (and only, in this case) thing to do.
这篇关于Java 字符串:“String s = new String(“silly");"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!