Example
Make a duplicate of the map and modify 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
The clone() method returns a shallow copy of the map as an Object, meaning it duplicates the map structure but not the objects it contains.
Therefore, the copied map references the same objects as the original map.
Note that since the return type is Object, it needs to be typecasted to HashMap for further usage.
Syntax
Technical Details
Returns:
|
A duplicate of the HashMap object.
|