且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用预定义值填充哈希图(java)

更新时间:2023-02-13 22:18:25

我会在设置 HashMap 时进行初始化

I would do the initialisation while setting up the HashMap

例如

private static final Map<String, String> m = new HashMap<String, String>() {{
    put("RC", "T1");
    put("AC", "T1");
}};

然后,您需要确保所有内容都在您的代码中一起设置.

Then you wuld make sure that everything is set up together in your code.

我认为@Nambari 提出了一个很好的观点,尽管它可能将值作为一个列表而不仅仅是一个字符串.不过,这确实会交换您的键和值.

I think @Nambari makes a good point though with perhaps having the value as a list rather than just a string. This does then swap your keys and values though.

例如

 private static final Map<String, List<String>> m = new HashMap<String, List<String>>() {{
    put("T1", Arrays.asList("RC", "AC");
}};