A technical aptitude question
HashMap map = new HashMap();
String key1 = \"key1\";
map.put(key1, \"value1\");
Stri
String
is an immutable object, so it needn't a clone
method since the client code can't change its state inside the String
class.
you can just ref to the original String
, for example:
String key2 = key1;// or using key1 directly instead.
As has been pointed out already, there is no need to clone immutable objects like String
.
But if you decide you really need a distinct instance of the string (and you nearly certainly don't), you can use the copy constructor:
String copy = new String(original);
System.out.println(copy.equals(original)); // true
System.out.println(copy == original); // false