EnumMap replace(K, V, V) in Java

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

Syntax:

boolean java.util.Map.replace(K key, V oldValue, V newValue)

This method takes three arguments. This method replaces the entry for the specified key only if currently mapped to the specified value.

Parameters: Three parameters are required for this method.

key: key with which the specified value is associated.

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

newValue: value to be associated with the specified key.

Returns: true if the value was replaced.

Throws:

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

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

3. NullPointerException - 

  1. If a specified key or newValue is null, and this map does not permit null keys or value.

  2. if oldValue is null and this map does not permit null values.

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

Approach

Java

import java.util.EnumMap;

public class EnumMapreplace2 {

    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.RED, "Red", "Red 1");

        System.out.println(enumMap);

    }
}

Output:

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


No comments:

Post a Comment