No clone method in String Class

前端 未结 2 1837
猫巷女王i
猫巷女王i 2021-01-03 15:42

A technical aptitude question

HashMap map = new HashMap();
String key1 = \"key1\";
map.put(key1, \"value1\");
Stri         


        
2条回答
  •  失恋的感觉
    2021-01-03 16:25

    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
    

提交回复
热议问题