No clone method in String Class

*爱你&永不变心* 提交于 2020-07-15 04:05:19

问题


A technical aptitude question

HashMap<String, String> map = new HashMap<String,String>();
String key1 = "key1";
map.put(key1, "value1");
String key2 = key1.clone();
map.put(key2, "value2");

What are the contents of the map object?

I answered it as {key1=value2} but later realized that String doesn't contain clone method.

I wanted to know the reason for the same.


回答1:


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.



回答2:


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


来源:https://stackoverflow.com/questions/44733836/no-clone-method-in-string-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!