简体   繁体   English

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

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

I have a class and it has a couple data structures in it among which is a hashmap. 我有一个类,它有几个数据结构,其中是一个hashmap。 But I want the hashmap to have default values so I need to preload it. 但是我希望hashmap具有默认值,所以我需要预加载它。 How do I do this since I can't use put method inside the object? 我怎么做这个因为我不能在对象里面使用put方法?

class Profile
{
    HashMap closedAges = new HashMap();
    closedAges.put("19");
}

I fixed it with this but I had to use a method within the object. 我用它修复了它,但我不得不在对象中使用一个方法。

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;
    }
}

You want to do this in the constructor of your class, for instance 例如,您希望在类的构造函数中执行此操作

class Example {

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

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

or to use the freakish double brace initialization feature of Java: 或者使用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");
      }};
   }
}

And finally, if your HashMap is a static field of your class, you can perform the initialization inside a static block: 最后,如果您的HashMap是类的静态字段,则可以在static块内执行初始化:

static {

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

In order to address Behes comment, if you are not using Java 7, fill the <> brackets with your type parameters, in this case <Integer, String> . 为了解决Behes注释,如果您不使用Java 7,请使用类型参数填充<>括号,在本例中为<Integer, String>

You could do this: 你可以这样做:

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

This java idiom is called double brace initialization .: 这个java习语称为双括号初始化 。:

The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. 第一个大括号创建一个新的AnonymousInnerClass,第二个大括号声明在实例化匿名内部类时运行的实例初始化程序块。

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

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