EnumMap remove(Object, Object) in Java

remove(Object, Object): This method is available in java.util.EnumMap class of Java.

Syntax:

boolean java.util.Map.remove(Object key, Object value)

This method takes two arguments of type Object as its parameters. This method removes the entry for the specified key only if it is currently mapped to the specified value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is associated.

value: value expected to be associated with the specified key.

Returns: true if the value was removed.

Throws:

1. UnsupportedOperationException - if the remove operation is not supported by this map.

2. ClassCastException - if the key or value is of an inappropriate type for this map.

3. NullPointerException - if the specified key or value is null,and this map does not permit null keys or values.

Approach 1: When no exception

Java

import java.util.EnumMap;

public class EnumMapremove2 {

    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        EnumMap<Colour, String> enumMap =
new EnumMap<Colour, String>(Colour.class);

        enumMap.put(Colour.RED, "Red");
        enumMap.put(Colour.GREEN, "Green");

        enumMap.put(Colour.YELLOW, "Yellow");
        enumMap.put(Colour.ORANGE, "Orange");

        enumMap.remove(Colour.RED, "Red");

        System.out.println(enumMap);

    }
}

Output:

{GREEN=Green, YELLOW=Yellow, ORANGE=Orange}


No comments:

Post a Comment