Question

I would like to make a copy of a string without having a string variable reference the previous string. Would the toString() method be the solution?

In other words, does String.toString() return a copy of its characters rather than a reference to itself?

Était-ce utile?

La solution

No, it returns the String object itself. You can do

String copy = new String(myString.toCharArray());

or

String copy = new String(myString); // may use same char[] instance

Please note String is immutable so usually you have no need to copy it.

Autres conseils

No, toString will return the String itself. If you want a copy you should use

String newString = new String(oldString);

but the internal implementation of strings in JDK uses a string pool so they could refer to the same internal string.

In any case asking for a copy doesn't make sense, since they're immutable: unless you are modifying the copy while you create it, there is no point in doing it at all.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance.

toString(): This returns a String object representing the value of this Integer.

toString(int i): This returns a String object representing the specified integer.

System.out.println("str.toString: " + str.toString());
 String s1 = "123";
 String s2 = "123";

These two are the same string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top