Java HashMapclone() Method
Example
Create a copy of a map and change it:
import java.util.HashMap;public class Main { public static void main(String[] args) { HashMap<String, String> capitalCities = new HashMap<String, String>(); capitalCities.put("England", "London"); capitalCities.put("Germany", "Berlin"); capitalCities.put("Norway", "Oslo"); capitalCities.put("USA", "Washington DC"); HashMap copy = (HashMap)capitalCities.clone(); copy.remove("England"); System.out.println(capitalCities); System.out.println(copy); }}Definition and Usage
Theclone() method returns a copy of the map as anObject.
This creates a "shallow" copy, which means that copies of objects in the map are not created, instead the map has references to the same objects that are in the original map.
Note: Since the return type isObject, it must betype casted in order to use it as aHashMap as shown in the example above.
Syntax
public Object clone()Technical Details
| Returns: | A copy of theHashMap object. |
|---|
Related Pages
❮ HashMap Methods

