How can I make a copy of a string that is not an alias, but a copy of all the characters that make up the string?

Ted pottel :

I would like to make a copy of a string and then have the ability to make changes to the copy without changing the whole string. I tried using String strTemplateTemp=new String(strTemplate); instead of String strTemplateTemp=strTemplate; I also tried using clone but got an error saying the clone method was not visible: String strTemplateTemp=strTemplate.clone();

My code

DefaultListModel<String> getAllMacrows()
{
    DefaultListModel<String> rows= new DefaultListModel<String>();
    int pes=0;
    int nameStart;
    int parEnd;     
    String row;
    String strTemplateTemp=new String(strTemplate);

    strTemplateTemp=strTemplateTemp.replace("\n"," ");
    // now both strTemplateTemp and  strTemplate have chnaged
    // want just strTemplateTemp to chnage
SDJ :

In Java String instances are immutable, so it is not possible to change the string (i.e., have a side effect). The statement:

 strTemplateTemp=strTemplateTemp.replace("\n"," ");

Creates a new string and assigns a reference to the new string to the variable strTemplateTemp.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. java.lang.String

See this post for details.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326886&siteId=1