我如何在一个对象中预加载一个hashmap(没有put方法)? [英] how do i preload a hashmap in an object(without put method)?

查看:333
本文介绍了我如何在一个对象中预加载一个hashmap(没有put方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


解决方案

你可以这样做:

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

这个java成语被称为 双重括号初始化 。:


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



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

解决方案

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.

这篇关于我如何在一个对象中预加载一个hashmap(没有put方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆