如何初始化静态地图? [英] How can I initialise a static Map?

查看:23
本文介绍了如何初始化静态地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何在 Java 中初始化静态 Map?

How would you initialise a static Map in Java?

方法一:静态初始化
方法二:实例初始化器(匿名子类)或者其他方法?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other method?

各自的优缺点是什么?

以下是说明这两种方法的示例:

Here is an example illustrating the two methods:

import java.util.HashMap;
import java.util.Map;

public class Test {
    private static final Map<Integer, String> myMap = new HashMap<>();
    static {
        myMap.put(1, "one");
        myMap.put(2, "two");
    }

    private static final Map<Integer, String> myMap2 = new HashMap<>(){
        {
            put(1, "one");
            put(2, "two");
        }
    };
}

推荐答案

在这种情况下,实例初始化器只是语法糖,对吧?我不明白为什么你需要一个额外的匿名类来初始化.如果创建的类是 final 的,它就不会工作.

The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.

您也可以使用静态初始化程序创建一个不可变的映射:

You can create an immutable map using a static initialiser too:

public class Test {
    private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }
}

这篇关于如何初始化静态地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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