What is the LinkedHashMap.clear() method in Java?
The LinkedHashMap class in Java is the same as the HashMap class, except LinkedHashMap maintains the insertion order, whereas HashMap does not.
The LinkedHashMap class uses a doubly-linked list to maintain the insertion order.
You can read more about the
LinkedHashMapclass here.
What is the clear() method in LinkedHashMap?
The clear() method of the LinkedHashMap class removes all of the key and value mappings from a specified LinkedHashMap object. After calling this method, the LinkedHashMap object becomes empty.
Syntax
public void clear()
This method doesn’t take any parameters and does not return a value.
Code
The code below shows how to use the clear() method.
import java.util.LinkedHashMap;class LinkedHashMapClearExample {public static void main( String args[] ) {LinkedHashMap<Integer, String> map = new LinkedHashMap<>();map.put(1, "one");map.put(2, "two");System.out.println("LinkedHashMap is : "+ map);map.clear();System.out.println("\nAfter Calling Clear method");System.out.println("\nLinkedHashMap is : " + map);}}
Explanation
In the code above:
-
In line 1, we import the
LinkedHashMapclass. -
From lines 5 to 8, we create a
LinkedHashMapobject and use theput()method to add two mappings ({1=one, 2=two}) tomap. -
In line 11, we use the
clear()method to remove all the mappings frommap. This makesmapempty. -
In line 14, we print
mapto ensure that it is empty.