How should I copy Strings in Java?

前端 未结 5 1885
遥遥无期
遥遥无期 2020-12-12 14:14
    String s = \"hello\";
    String backup_of_s = s;
    s = \"bye\";

At this point, the backup variable still contains the original value \"hello

相关标签:
5条回答
  • 2020-12-12 14:38

    Your second version is less efficient because it creates an extra string object when there is simply no need to do so.

    Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.

    0 讨论(0)
  • 2020-12-12 14:40

    Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

    So you can copy as in your first example without any problem :

    String s = "hello";
    String backup_of_s = s;
    s = "bye";
    
    0 讨论(0)
  • 2020-12-12 14:47
    String str1="this is a string";
    String str2=str1.clone();
    

    How about copy like this? I think to get a new copy is better, so that the data of str1 won't be affected when str2 is reference and modified in futher action.

    0 讨论(0)
  • 2020-12-12 14:49

    Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.

    0 讨论(0)
  • 2020-12-12 14:51

    Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

    With this in mind, the first version should be preferred.

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