EnumMap replace(K, V) in Java

replace(K, V): This method is available in java.util.EnumMap class of Java.

Syntax:

String java.util.Map.replace(K key, V value)

This method takes two arguments. This method replaces the entry for the specified key only if it is currently mapped to some value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is associated.

value: value to be associated with the specified key.

Returns: the previous value associated with the specified key, or null if there was no mapping for the key.

Throws:

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

2. ClassCastException - if the class of the specified key or value prevents it from being stored in this map.

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

4. IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map.

Approach

Java

import java.util.EnumMap;

public class EnumMapreplace {

    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.replace(Colour.GREEN, "Green 1");

        System.out.println(enumMap);

    }
}

Output:

{RED=Red, GREEN=Green 1, YELLOW=Yellow, ORANGE=Orange}


No comments:

Post a Comment