bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java HashMap clone() Method

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java HashMap clone() Method?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ java.util.HashMap;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The clone() method returns a copy of the map as an Object .
Definition and Usage
Java HashMap clone() Method

❮ HashMap Methods

Example

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 copy of the map as an Object .

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 is Object , it must be type casted in order to use it as a HashMap as shown in the example above.

Syntax

public Object clone()

Technical Details

Returns:A copy of the HashMap object.

Previous

Java HashMap clear() Method

Next

Java HashMap compute() Method