Should I use put() or putIfAbsent() after using getOrDefault()?

后端 未结 2 811
萌比男神i
萌比男神i 2020-12-16 15:52

Java8 introduced those nice methods getOrDefault() and putIfAbsent(), allowing to write code like:

Map>          


        
2条回答
  •  遥遥无期
    2020-12-16 16:18

    An important point about computeIfAbsent is that it takes a Function which will only get executed if the Key is absent and we need a default Value.

    Whereas getOrDefault requires the default Value itself, already computed. In this case, the default Value we would need is a new ArrayList(), which has the side effect of allocating a new object on the heap.

    We want to defer doing that until we are sure that the key isn't already in itemsByFoo. Otherwise we would be generating unnecessary garbage for gc to collect.

提交回复
热议问题