[英]how do i preload a hashmap in an object(without put method)?
我有一個類,它有幾個數據結構,其中是一個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;
}
}
例如,您希望在類的構造函數中執行此操作
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>
。
你可以這樣做:
Map<String, String> map = new HashMap<String, String>() {{
put("1", "one");
put("2", "two");
put("3", "three");
}};
這個java習語稱為雙括號初始化 。:
第一個大括號創建一個新的AnonymousInnerClass,第二個大括號聲明在實例化匿名內部類時運行的實例初始化程序塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.