我想制作一个字符串的副本,然后能够在不更改整个字符串的情况下对副本进行更改。我尝试使用
String strTemplateTemp=new String(strTemplate);而不是
String strTemplateTemp=strTemplate;我也尝试使用,clone但是收到一条错误消息,指出不可见clone方法:String strTemplateTemp=strTemplate.clone();
我的密码
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
Run Code Online (Sandbox Code Playgroud)
在Java中,String实例是不可变的,因此无法更改字符串(即具有副作用)。该声明:
strTemplateTemp=strTemplateTemp.replace("\n"," ");
Run Code Online (Sandbox Code Playgroud)
创建一个新字符串,并将对新字符串的引用分配给变量strTemplateTemp。
字符串是常量;它们的值创建后无法更改。字符串缓冲区支持可变字符串。由于String对象是不可变的,因此可以共享它们。java.lang.String
有关详细信息,请参见此帖子。