Java Strings: “String s = new String(”silly“);”

前端 未结 23 2462

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\");         


        
23条回答
  •  名媛妹妹
    2020-11-22 14:46

    CaseInsensitiveString and String are different objects. You can't do:

    CaseInsensitiveString cis = "Polish";
    

    because "Polish" is a String, not a CaseInsensitiveString. If String extended CaseInsensitiveString String then you'd be OK, but obviously it doesn't.

    And don't worry about the construction here, you won't be making unecessary objects. If you look at the code of the constructor, all it's doing is storing a reference to the string you passed in. Nothing extra is being created.

    In the String s = new String("foobar") case it's doing something different. You are first creating the literal string "foobar", then creating a copy of it by constructing a new string out of it. There's no need to create that copy.

提交回复
热议问题