1

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?

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

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

4

2 回答 2

5
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.

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

于 2012-05-10T15:33:30.673 回答
4

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

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

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

于 2012-05-10T15:36:17.570 回答