What is the purpose of the expression “new String(…)” in Java?

后端 未结 9 1059
迷失自我
迷失自我 2020-11-22 02:39

While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.

For example

9条回答
  •  孤独总比滥情好
    2020-11-22 03:18

    Here is a quote from the book Effective Java Third Edition (Item 17: Minimize Mutability):

    A consequence of the fact that immutable objects can be shared freely is that you never have to make defensive copies of them (Item 50). In fact, you never have to make any copies at all because the copies would be forever equivalent to the originals. Therefore, you need not and should not provide a clone method or copy constructor (Item 13) on an immutable class. This was not well understood in the early days of the Java platform, so the String class does have a copy constructor, but it should rarely, if ever, be used.

    So It was a wrong decision by Java, since String class is immutable they should not have provided copy constructor for this class, in cases you want to do costly operation on immutable classes, you can use public mutable companion classes which are StringBuilder and StringBuffer in case of String.

提交回复
热议问题