繁体   English   中英

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

[英]how do i preload a hashmap in an object(without put method)?

我有一个类,它有几个数据结构,其中是一个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");
   }
}

或者使用Java的奇特双括号初始化功能:

class Example {

   Map<Integer, String> data;

   public Example() {
        /* here the generic type parameters cannot be omitted */
        data = new HashMap<Integer, String>() {{
           put(1, "Hello");
           put(2, "World");
      }};
   }
}

最后,如果您的HashMap是类的静态字段,则可以在static块内执行初始化:

static {

   data.put(1, "Hello");
   ...
}

为了解决Behes注释,如果您不使用Java 7,请使用类型参数填充<>括号,在本例中为<Integer, String>

你可以这样做:

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

这个java习语称为双括号初始化 。:

第一个大括号创建一个新的AnonymousInnerClass,第二个大括号声明在实例化匿名内部类时运行的实例初始化程序块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM