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

前端 未结 23 2393

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:24

    In your first example, you are creating a String, "silly" and then passing it as a parameter to another String's copy constructor, which makes a second String which is identical to the first. Since Java Strings are immutable (something that frequently stings people who are used to C strings), this is a needless waste of resources. You should instead use the second example because it skips several needless steps.

    However, the String literal is not a CaseInsensitiveString so there you cannot do what you want in your last example. Furthermore, there is no way to overload a casting operator like you can in C++ so there is literally no way to do what you want. You must instead pass it in as a parameter to your class's constructor. Of course, I'd probably just use String.toLowerCase() and be done with it.

    Also, your CaseInsensitiveString should implement the CharSequence interface as well as probably the Serializable and Comparable interfaces. Of course, if you implement Comparable, you should override equals() and hashCode() as well.

    0 讨论(0)
  • 2020-11-22 14:24

    CaseInsensitiveString is not a String although it contains a String. A String literal e.g "example" can be only assigned to a String.

    0 讨论(0)
  • 2020-11-22 14:24

    First, you can't make a class that extends from String, because String is a final class. And java manage Strings differently from other classes so only with String you can do

    String s = "Polish";
    

    But whit your class you have to invoke the constructor. So, that code is fine.

    0 讨论(0)
  • 2020-11-22 14:27

    I would just add that Java has Copy constructors...

    Well, that's an ordinary constructor with an object of same type as argument.

    0 讨论(0)
  • 2020-11-22 14:28

    The best way to answer your question would be to make you familiar with the "String constant pool". In java string objects are immutable (i.e their values cannot be changed once they are initialized), so when editing a string object you end up creating a new edited string object wherease the old object just floats around in a special memory ares called the "string constant pool". creating a new string object by

    String s = "Hello";
    

    will only create a string object in the pool and the reference s will refer to it, but by using

    String s = new String("Hello");
    

    you create two string objects: one in the pool and the other in the heap. the reference will refer to the object in the heap.

    0 讨论(0)
  • 2020-11-22 14:29

    Just because you have the word String in your class, does not mean you get all the special features of the built-in String class.

    0 讨论(0)
提交回复
热议问题