Java字符串:" String s = new String(" silly");" [英] Java Strings: "String s = new String("silly");"

查看:132
本文介绍了Java字符串:" String s = new String(" silly");"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名学习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";




  1. 为什么第一个声明没问题?不应该是

  1. Why is the first statement ok? Shouldn't it be

CaseInsensitiveString cis =Polish;

如何使 CaseInsensitiveString 表现得像 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 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");"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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