6

Why String class is not implementing Cloneable interface?

For example: (We write this type of code sometimes.)

String s1 = new String("Hello");

String s2 = new String("Hello");

Here s1!=s2;

So instead of doing this , if we could have done:

String s1 = new String("Hello");

String s2 = s1.clone();

This could be easy.

Raj
  • 692
  • 2
  • 9
  • 23
  • 4
    Why would it...? Why would you want to duplicate/clone an immutable object. – Sotirios Delimanolis Mar 18 '14 at 18:55
  • Just do `String s2 = s1;`. No one can break that. – Sotirios Delimanolis Mar 18 '14 at 18:58
  • 2
    If you think you really have a need for two `String` references to be different even though the values might be the same, I'd suggest you rethink your design. It probably means you're trying to do something "clever", to save a bit of typing, instead of coding what you mean. And not only is clever code less readable, anyone who sees `s1==s2` or `s1!=s2` in your code will probably think you made a newbie mistake. – ajb Mar 18 '14 at 19:01
  • 1
    It seems that this may be [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Maybe instead of asking about `s1.clone();` explain why do you need separate instance of immutable object? – Pshemo Mar 18 '14 at 19:02
  • @SotiriosDelimanolis ,but this will copy the reference ,not the content . – SteveL Mar 18 '14 at 19:06
  • @SteveL Why does that matter? In this case? – Sotirios Delimanolis Mar 18 '14 at 19:23
  • @SotiriosDelimanolis ,he wants it to be s1!=s2 ,thats the point of the question – SteveL Mar 18 '14 at 21:02
  • @SteveL Right. And we've established there's no point. – Sotirios Delimanolis Mar 18 '14 at 21:04

3 Answers3

4

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

You can clone string with

String clonedString = new String(stringToClone);

so

String s1 = new String("Hello");
String s2 = new String(s1);
ajb
  • 31,309
  • 3
  • 58
  • 84
Gaskoin
  • 2,469
  • 13
  • 22
  • 1
    But see the other answers: If your solution requires you to clone an immutable object, then your solution probably is some kind of a sneaky/clever trick that will be hard for other programmers to understand. That's almost always a Bad Thing. – Solomon Slow Mar 18 '14 at 19:13
0

Here's another way:

String s2 = s1.concat("");
Urdans
  • 1