如何在不使用静态块的情况下在类级别初始化hashmap

时间:2015-07-30 10:19:44

标签: java spring hashmap

我想初始化一个Hashmap,但我不想使用Constructor方式,我也不想在静态块中初始化它。你能告诉我怎么做吗?

public ClassName() {
    idToSkillREs = new HashMap();
}

我不想以这种方式使用

3 个答案:

答案 0 :(得分:5)

您可以简单地将其声明为实例成员,并立即初始化。

Map<Type,Type> idToSkillREs = new HashMap<Type,Type>();

public ClassName() {

}

这不是构造函数,也不是静态块。

答案 1 :(得分:1)

初始化(非静态)块怎么样?

public class ClassName() {

    Map<Type, Type> idToSkillREs; // nothing here

    {
        idToSkillREs= new HashMap<Type,Type>(); // this will run before the constructor
    }

    public Classname() {
        // constructor code
    }
}

答案 2 :(得分:1)

我认为这符合资格。我们在类级&#34;上创建Map&#34;并通过添加一些条目(!!)来初始化它...所有这些都没有静态初始化块。

public class Example {
    private static final Map<String, String> skillz =
         new HashMap<String><String>(){{
             put("knitting", "excellent");
             put("macrame", "passable");
             put("sword-fighting", "poor");
         }};
    ...
}