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

十年热恋 提交于 2019-12-10 18:49:52

问题


I have a class and it has a couple data structures in it among which is a hashmap. But I want the hashmap to have default values so I need to preload it. How do I do this since I can't use put method inside the object?

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

回答1:


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.:

The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated.




回答2:


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:

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:

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>.



来源:https://stackoverflow.com/questions/11352396/how-do-i-preload-a-hashmap-in-an-objectwithout-put-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!