延迟实例化地图值 [英] lazy instantiation of the map value

查看:130
本文介绍了延迟实例化地图值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法实例化 map 懒惰的值



例如

  class MapTest {
@Lazy(soft = true)HashMap< String,List< String>>地图
}

这样做我可以使用这个调用并获得 null 没有收到 NullPointerException

  new MapTest()。map.key1 

然而试图调用

  map.key1.remove(1)

会因值为 null 而导致 NullPointerException 。 (如果它抛出 IndexOutOfBounds 异常就可以了)



有没有办法实例化列表地图的值?

解决方案

尝试 map.withDefault

  def map = [:]。withDefault {[]} 
断言map.key1.isEmpty()

groovy方法来实例化一个空的哈希映射
  • withDefault 是一个常用的方法,如果该值不存在,则每次请求密钥初始化该值时都会调用该闭包。这个闭包需要一个参数(关键),并且值

  • []是创建空列表的常规方式 - {[]}是一个闭包,它为每个返回一个空列表关键



  • 查看其他示例 here

    Is there a way to instantiate the value of map lazy?

    For example

    class MapTest {
        @Lazy(soft = true) HashMap<String, List<String>> map
    }
    

    Doing like this I can use this call and get null without recieving NullPointerException

    new MapTest().map.key1
    

    However attempt to call

    map.key1.remove(1) 
    

    will lead to NullPointerException due the value being null. (it would be fine if it threw IndexOutOfBounds exception)

    Is there a way to instantiate the list value of the map?

    解决方案

    try map.withDefault :

    def map = [:].withDefault { [] }
    assert map.key1.isEmpty()
    

    Some explanation :

    • [:] is the groovy way to instantiate an empty hash map
    • withDefault is a groovy method on a map wich take a closure. this closure is call every time a key is requested to initialize the value if it doesn't exist. this closure take one parameter (the key) and should the value
    • [] is the groovy way to create an empty list - { [] } is a closure wich return an empty list for every key

    see others examples here

    这篇关于延迟实例化地图值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆