title: Shallow copy of a Map in Java
body: <p>As I understand it, there are a couple of ways (maybe others as well) to create a shallow copy of a <code>Map</code> in Java:</p>
  
  <pre><code>Map&lt;String, Object&gt; data = new HashMap&lt;String, Object&gt;();
  Map&lt;String, Object&gt; shallowCopy;
  
  // first way
  shallowCopy = new HashMap&lt;String, Object&gt;(data);
  
  // second way
  shallowCopy = (Map&lt;String, Object&gt;) ((HashMap&lt;String, Object&gt;) data).clone();
  </code></pre>
  
  <p>Is one way preferred over the other, and if so, why?</p>
  
  <p>One thing worth mentioning is that the second way gives an "Unchecked Cast" warning. So you have to add <code>@SuppressWarnings("unchecked")</code> to get around it, which is a little irritating (see below).</p>
  
  <pre><code>@SuppressWarnings("unchecked")
  public Map&lt;String, Object&gt; getDataAsMap() {
      // return a shallow copy of the data map
      return (Map&lt;String, Object&gt;) ((HashMap&lt;String, Object&gt;) data).clone();
  }
  </code></pre>