Java中如何初始化并填充嵌套不可变Map结构
解决Guava嵌套ImmutableMap初始化问题
你的问题出在两处核心错误:
- 错误调用实例方法:
ImmutableMap.put()是实例方法,不能直接通过类名调用——必须通过ImmutableMap的实例或者其Builder来添加键值对。 - put方法参数不符合签名:外层Builder的
put()每次仅接受一组「键-值」对,你不能把多个内层Map作为参数塞进同一个put里。
正确写法1:用ImmutableMap.of()构建内层Map(适合键值对少的场景)
private static ImmutableMap<String, ImmutableMap<String, String[]>> Errors = ImmutableMap.<String, ImmutableMap<String, String[]>>builder() // 给外层Map添加一组键值对:外层key对应一个完整的内层ImmutableMap .put( PppoeAgentStatTypes.RECEIVED.getCounterType(), ImmutableMap.of( // 内层Map的第一个键值对 PppoeAgentCounters.AC_SYSTEM_ERROR.getCounterType(), new String[]{PppoeAgentCounters.PADS.getCounterType(), PppoeAgentCounters.PADO.getCounterType()}, // 内层Map的第二个键值对 PppoeAgentCounters.SERVICE_NAME_ERROR.getCounterType(), new String[]{PppoeAgentCounters.PADS.getCounterType(), PppoeAgentCounters.PADO.getCounterType()} ) ) // 可继续添加更多外层键值对 // .put(anotherOuterKey, anotherInnerImmutableMap) .build();
正确写法2:用Builder构建内层Map(适合键值对多的场景)
如果内层Map的键值对数量较多,用Builder会更清晰易读:
private static ImmutableMap<String, ImmutableMap<String, String[]>> Errors = ImmutableMap.<String, ImmutableMap<String, String[]>>builder() .put( PppoeAgentStatTypes.RECEIVED.getCounterType(), ImmutableMap.<String, String[]>builder() .put(PppoeAgentCounters.AC_SYSTEM_ERROR.getCounterType(), new String[]{PppoeAgentCounters.PADS.getCounterType(), PppoeAgentCounters.PADO.getCounterType()}) .put(PppoeAgentCounters.SERVICE_NAME_ERROR.getCounterType(), new String[]{PppoeAgentCounters.PADS.getCounterType(), PppoeAgentCounters.PADO.getCounterType()}) .build() // 先构建内层Map ) .build(); // 再构建外层Map
保持原类型声明的写法
如果需要保留原代码的Map<String, Map<String, String[]>>类型,只需调整泛型声明即可(ImmutableMap实现了Map接口):
private static Map<String, Map<String, String[]>> Errors = ImmutableMap.<String, Map<String, String[]>>builder() .put( PppoeAgentStatTypes.RECEIVED.getCounterType(), ImmutableMap.of( PppoeAgentCounters.AC_SYSTEM_ERROR.getCounterType(), new String[]{PppoeAgentCounters.PADS.getCounterType(), PppoeAgentCounters.PADO.getCounterType()}, PppoeAgentCounters.SERVICE_NAME_ERROR.getCounterType(), new String[]{PppoeAgentCounters.PADS.getCounterType(), PppoeAgentCounters.PADO.getCounterType()} ) ) .build();
内容的提问来源于stack exchange,提问作者baris
相关产品推荐
相关产品推荐

