从参数将字符串内容分配给 Java 中的新字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10537390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:29:14  来源:igfitidea点击:

Assign a String content to a new String in Java from parameter

javastringnetbeanswarnings

提问by Hernán Eche

Having this method

有了这个方法

void doSomething(String input)
{
   //trick for create new object instead of reference assignment
   String workStr= "" + input; 

   //work with workStr
}

Which is the java way for doing that?

这样做的java方式是什么?

Edit

编辑

  • if I use input variable as input=something then Netbeans warns about assigning a value to a method parameter
  • If I create it with new String(input) it warns about using String constructor
  • 如果我使用输入变量作为 input=something 那么 Netbeans 会警告为方法参数赋值
  • 如果我用 new String(input) 创建它,它会警告使用 String 构造函数

Perhaps the solution is not to assign nothing to input, or just ignore the warning..

也许解决方案不是不为输入分配任何内容,或者只是忽略警告..

回答by Mario F

String copy = new String(original);

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

初始化新创建的 String 对象,使其表示与参数相同的字符序列;换句话说,新创建的字符串是参数字符串的副本。除非需要原始的显式副本,否则不需要使用此构造函数,因为字符串是不可变的。

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String(java.lang.String)

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String(java.lang.String)

回答by Attila

Strings in java are immutable, which means you cannot change the object itself (any operation returning a string (e.g. substring) will return a new one).

Stringjava 中的 s 是不可变的,这意味着您不能更改对象本身(任何返回字符串(例如子字符串)的操作都将返回一个新的)。

This means there is no need to create a new object for Strings, as there is no way for you to modify the original. Any attempt to do so will just result in wasted memory.

这意味着无需为Strings创建新对象,因为您无法修改原始对象。任何这样做的尝试只会导致内存浪费。

Assigning references is only a problem when the objects in question are mutable, because changes in one object will reflect in all other copies of the same reference.

仅当所讨论的对象是可变的时,分配引用才是一个问题,因为一个对象的更改将反映在同一引用的所有其他副本中。