Creating a map using withDefault that calls null when an item is set

I'm trying to use the Groovy creation method TreeMap<String, List<Data>>with default values, so I easily add data to the new list if the key is not already present.

TreeMap<String, List<Data>> myData = (TreeMap<String, List<Data>>) [:].withDefault { [] }

As you can see, I have a requirement to use TreeMap, but it withDefaultreturns an instance Map, so I need to do it.

When I try to add a new list to the map,

myData[newKey].add(newData)

myData[newKey]makes up null. However, if I change the initialization Mapto remove the casting TreeMap(and change the type only to Mapinstead TreeMap), it myData[newKey].add(newData)works as expected.

What are the reasons for this? Can I use withDefaultif I draw a map?

+4
1

. . :

def map1 = [:].withDefault { 0 }
TreeMap map2 = map1

map1 groovy.lang.MapWithDefault map2 java.util.TreeMap. , , . map2 , . :

def map1 = [:].withDefault { 0 }
TreeMap map2 = new TreeMap(map1)

, . .

:

TreeMap<String, List<Data>> myData = (TreeMap<String, List<Data>>) [:].withDefault { [] }

:

def tmpMap = [:].withDefault { [] }
TreeMap<String, List<Data>> myData = (TreeMap<String, List<Data>>)tmpMap

, .

EDIT:

- - :

Set names = new HashSet()
ArrayList namesList = names

ArrayList, , ArrayList namesList = new ArrayList(names). , , , . , Groovy . ArrayList. TreeMap<String, List<Data>>.

+2

Source: https://habr.com/ru/post/1548357/


All Articles