2

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.

Bonny Mathew
  • 171
  • 1
  • 7
  • 4
    A String is immutable. There is no reason to clone it. Why do you think it could be useful? – JB Nizet Jun 24 '17 at 07:12
  • 1
    I'm a bit confused by the question, "what are the contents of the map object?" The code doesn't compile, so there is no map object, or anything else. You're asking us to talk about the state of something that can't exist. – yshavit Jun 24 '17 at 07:22
  • Actually, `String` does have a `clone()` method, inherited from `Object`; it is just `protected`, and would throw `CloneNotSupportedException` if invoked. – Andy Turner Jun 25 '17 at 08:53

2 Answers2

5

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.
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • For an example, if you store a cookie from WebView (Java Android) that is a String, and use it to check if a notification should be displayed, when you close your application or reset you phone, WebView CookieManager will be dumped from memory and you'll lose your data, what not would happen if you use a "static String variable". Then we have a problem with the nature of the manager of object. – UserOfStackOverFlow Sep 15 '21 at 12:08
3

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
Andy Turner
  • 137,514
  • 11
  • 162
  • 243