Java 如何在对象中预加载hashmap(没有put方法)?

Java 如何在对象中预加载hashmap(没有put方法)?,java,map,hashmap,Java,Map,Hashmap,我有一个类,它有几个数据结构,其中有一个hashmap。但是我希望hashmap有默认值,所以我需要预加载它。既然我不能在对象内部使用put方法,我该怎么做 class Profile { HashMap closedAges = new HashMap(); closedAges.put("19"); } 我用这个修复了它,但是我必须在对象中使用一个方法 class Profile { HashMap closedAges = loadAges(); H

我有一个类,它有几个数据结构,其中有一个hashmap。但是我希望hashmap有默认值,所以我需要预加载它。既然我不能在对象内部使用put方法,我该怎么做

class Profile
{
    HashMap closedAges = new HashMap();
    closedAges.put("19");
}
我用这个修复了它,但是我必须在对象中使用一个方法

class Profile
{   
    HashMap closedAges = loadAges();
    HashMap loadAges()
    {
        HashMap closedAges = new HashMap();

        String[] ages = {"19", "46", "54", "56", "83"};
        for (String age : ages)
        {
            closedAges.put(age, false);
        }
        return closedAges;
    }
}

例如,您希望在类的构造函数中执行此操作

class Example {

   Map<Integer, String> data = new HashMap<>();

   public Example() {
      data.put(1, "Hello");
      data.put(2, "World");
   }
}

为了处理Behes的评论,如果您没有使用Java 7,请用您的类型参数填充
括号,在本例中,您可以执行以下操作:

Map<String, String> map = new HashMap<String, String>() {{
   put("1", "one");
   put("2", "two");
   put("3", "three");
}};
Map Map=newhashmap(){{
付诸表决(“1”、“1”);
付诸表决(“2”、“2”);
付诸表决(“3”、“3”);
}};
这个java习语被称为:

第一个大括号创建一个新的AnonymousInnerClass,第二个大括号声明一个实例初始值设定项块,该块在实例化匿名内部类时运行


为什么不能使用hashmap方法?代码现在是什么样子的?您尝试过获得想要的东西吗?为什么不能使用put()方法?我不明白这一点。@Todd我是在方法之外做这件事的,因为我想马上初始化一个HashMap,就像你可以使用字符串数组一样。@Behe想详细说明一下吗?你是否缺少类型参数?@Behe-在实例化中省略泛型类型是Java 7的一个新功能。然后我必须重新措辞我的注释:那不会在没有Java 7的情况下这样做。对于双括号,您可以使用justput而不是data.put.Wow,谢谢。你能解释一下它的工作原理吗?我以前从未见过双括号,尤其是在变量声明中。
static {

   data.put(1, "Hello");
   ...
}
Map<String, String> map = new HashMap<String, String>() {{
   put("1", "one");
   put("2", "two");
   put("3", "three");
}};