我有一个类,它有几个数据结构,其中有一个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;
}
}
答案 0 :(得分:11)
您希望在类的构造函数中执行此操作,例如
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>
。
答案 1 :(得分:7)
你可以这样做:
Map<String, String> map = new HashMap<String, String>() {{
put("1", "one");
put("2", "two");
put("3", "three");
}};
这个java习语称为double brace initialization:
第一个大括号创建一个新的AnonymousInnerClass,第二个大括号声明在实例化匿名内部类时运行的实例初始化程序块。