Map.of, Unmodifiable and UnsupportedOperationException

The convenience Map.of method creates an unmodifiable Map:


@Test
public void changingImmutableMapCausesException() {
    var messages = Map.of("message", "not nice");
    assertThrows(UnsupportedOperationException.class,
            () -> messages.put("message", "nice")
    );
}

A modification of an umodifiable Map causes:


java.lang.UnsupportedOperationException
    at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
    at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:1072)    

To modify the Map, create a new Map, then modify (add, remove, change):


@Test
public void copyMapAndModify() {
    var messages = Map.of("message", "not nice");
    var copiedMessages = new HashMap<String,String>(messages);
    copiedMessages.put("message", "nice");
    assertEquals(copiedMessages.get("message"),"nice");
}

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments
License