我有一个类,它有几个数据结构,其中是一个hashmap.但是我希望hashmap具有默认值,所以我需要预加载它.我怎么做这个因为我不能在对象里面使用put方法?
class Profile
{
HashMap closedAges = new HashMap();
closedAges.put("19");
}
Run Code Online (Sandbox Code Playgroud)
我用它修复了它,但我不得不在对象中使用一个方法.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Kon*_*che 11
例如,您希望在类的构造函数中执行此操作
class Example {
Map<Integer, String> data = new HashMap<>();
public Example() {
data.put(1, "Hello");
data.put(2, "World");
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用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");
}};
}
}
Run Code Online (Sandbox Code Playgroud)
最后,如果您的类HashMap是静态字段,则可以在static块内执行初始化:
static {
data.put(1, "Hello");
...
}
Run Code Online (Sandbox Code Playgroud)
为了解决Behes注释,如果您不使用Java 7,<>请在这种情况下使用类型参数填充括号<Integer, String>.
你可以这样做:
Map<String, String> map = new HashMap<String, String>() {{
put("1", "one");
put("2", "two");
put("3", "three");
}};
Run Code Online (Sandbox Code Playgroud)
这个java习语称为双括号初始化.:
第一个大括号创建一个新的AnonymousInnerClass,第二个大括号声明在实例化匿名内部类时运行的实例初始化程序块.
| 归档时间: |
|
| 查看次数: |
2639 次 |
| 最近记录: |