Why String class is not Cloneable?

会有一股神秘感。 提交于 2019-12-04 08:42:58

The String class represents an immutable string. There would be no purpose to cloning a String. If you feel that you need to clone it, then you can just reuse the same reference and achieve the same effect.

Even if you could clone s1 as s2, then s1 != s2 would still be true. They'd still be references to distinct objects.

Gaskoin

You can clone string with

String clonedString = new String(stringToClone);

so

String s1 = new String("Hello");
String s2 = new String(s1);

Here's another way:

String s2 = s1.concat("");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!