#序號 | ##建構子及描述 |
1 |
EnumMap(Class keyType)該建構函式使用指定的鍵類型創建一個空的枚舉映射。
|
2 |
EnumMap(EnumMap m)#該建構函數使用與指定的枚舉映射相同的鍵類型建立一個枚舉映射,
最初包含相同的映射(如果有)。
|
3 |
EnumMap(Map m)#此構造函數建立一個從指定映射初始化的枚舉映射。
|
table>範例讓我們看一個範例- 現場示範import java.util.EnumMap;
public class Demo {
// create an enum
public enum Numbers {
ONE, TWO, THREE, FOUR, FIVE
};
public static void main(String[] args) {
EnumMap<Numbers, String> map1 = new EnumMap<Numbers, String>(Numbers.class);
EnumMap<Numbers, String> map2 = new EnumMap<Numbers, String>(Numbers.class);
// associate values in map1
map1.put(Numbers.ONE, "1");
map1.put(Numbers.TWO, "2");
map1.put(Numbers.THREE, "3");
map1.put(Numbers.FOUR, "4");
// print the whole map
System.out.println("map1:" + map1);
// clone map1 to map2
map2 = map1.clone();
// print map2
System.out.println("map2:" + map2);
}
}
輸出map1:{ONE=1, TWO=2, THREE=3, FOUR=4}
map2:{ONE=1, TWO=2, THREE=3, FOUR=4}
範例讓我們看另一個範例,其中我們顯示了Map中鍵值對應的計數: 即時示範import java.util.*;
public class EnumMapDemo {
// create an enum
public enum Numbers {
ONE, TWO, THREE, FOUR, FIVE
};
public static void main(String[] args) {
EnumMap<Numbers, String> map = new EnumMap<Numbers, String>(Numbers.class);
// assosiate values in map
map.put(Numbers.ONE, "1");
map.put(Numbers.TWO, "2");
map.put(Numbers.THREE, "3");
map.put(Numbers.FOUR, "4");
// print the map
System.out.println("Map: " + map);
// print the number of mappings of this map
System.out.println("Number of mappings:" + map.size());
// remove value from Numbers.THREE
map.put(Numbers.FIVE, "5");
// print the new number of mappings of this map
System.out.println("Number of mappings:" + map.size());
}
}
輸出Map: {ONE=1, TWO=2, THREE=3, FOUR=4}
Number of mappings:4
Number of mappings:5