Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

clone()

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

public Object clone()

Technical Details

Returns:

A duplicate of the HashMap object.