Home » Java programming language

Java WeakHashMap remove() Method with Example

WeakHashMap Class remove() method: Here, we are going to learn about the remove() method of WeakHashMap Class with its syntax and example.
Submitted by Preeti Jain, on February 23, 2020

WeakHashMap Class remove() method

  • remove() method is available in java.util package.
  • remove() method is used to delete or remove the mappings for the given key element (key_ele) when it exists.
  • remove() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • remove() method does not throw an exception at the time of removing an element.

Syntax:

    public Object remove(Object key_ele);

Parameter(s):

  • Object key_ele – represents the key element (key_ele) whose linking element is to be deleted.

Return value:

The return type of the method is Object, it returns the associated value for the given key element (key_ele) when exists otherwise it returns null.

Example:

// Java program to demonstrate the example 
// of Object remove(Object key_ele)  
// method of WeakHashMap 

import java.util.*;

public class RemoveOfWeakHashMap {
    public static void main(String[] args) {
        // Instantiates a WeakHashMap object
        Map < Integer, String > map = new WeakHashMap < Integer, String > ();

        // By using put() method is to add
        // key-value pairs in a WeakHashMap
        map.put(10, "C");
        map.put(20, "C++");
        map.put(50, "JAVA");
        map.put(40, "PHP");
        map.put(30, "SFDC");

        // Display WeakHashMap
        System.out.println("WeakHashMap: " + map);

        // By using remove() method is to remove 
        // the mappings exists for the given key
        // element in this WeakHashMap
        map.remove(50);

        // Display Modified WeakHashMap
        System.out.print("map.remove(50): " + map);
    }
}

Output

WeakHashMap: {30=SFDC, 40=PHP, 10=C, 20=C++, 50=JAVA}
map.remove(50): {30=SFDC, 40=PHP, 10=C, 20=C++}



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.