70 likes | 207 Views
EnumMap. EnumMap is simiply a map with Enum type keys. Null keys are not allowed. "Map" is used by Java, C++ "Dictionary" is used by .Net , Python "Associative array" is used by Javascript , PHP. Enumeration Introduced to java in 5.0 The old way to fake an " enum ":
E N D
EnumMap EnumMap is simiply a map with Enum type keys. Null keys are not allowed. "Map" is used by Java, C++"Dictionary" is used by .Net, Python"Associative array" is used by Javascript, PHP
Enumeration Introduced to java in 5.0 The old way to fake an "enum": public static final int JERRY = 1; public static final int BOBBY = 2 ; public static final int PHIL = 3; //set selectedBandMember if (selectedBandMember == JERRY) //do stuff The new way to use an "enum": public enum Members { JERRY, BOBBY, PHIL }; public Members SelectedBandMember; //set selectedBandMember if (selectedBandMember == Members.JERRY) //do stuff .equals() and == both work switch and if statements both work
Constructors EnumMap(Class<K> keyType) : Creates an empty enum map with the specified key type. EnumMap(EnumMap<K,? extends V> m) : Creates an enum map with the same key type as the specified enum map, initially containing the same mappings (if any). EnumMap(Map<K,? extends V> m) : Creates an enum map initialized from the specified map.
public enumEnumKeys{ ONE, TWO, THREE } import java.util.EnumMap; import java.util.Set; public class EnumMapTest { public static void main(String[] args) { EnumMap<EnumKeys, Integer> eMap = new EnumMap<EnumKeys, Integer>(EnumKeys.class); eMap.put(EnumKeys.ONE, 1); eMap.put(EnumKeys.TWO, 2); eMap.put(EnumKeys.THREE, 3); Set<EnumKeys> keySet = eMap.keySet(); for (EnumKeys key : keySet) { System.out.println("ENUMMAP VALUE:"+ eMap.get(key)); }}}
Includes: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.EnumMap; import java.util.Set; Local Variables: EnumMap< EnumKeys,Integer> eMap= new EnumMap< EnumKeys,Integer>(EnumKeys.class); BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in)); Set< EnumKeys > keySet = eMap.keySet();
public class EnumMapTest { public static void main(String[] args) { try { for (EnumKeys key : EnumKeys.values()) { System.out.println("Enter Value for " + key.toString()); eMap.put(key, Integer.parseInt(br.readLine())); } catch (NumberFormatException e) {} catch (IOException e) {} for (EnumKeys key : keySet) { System.out.println("Key: " + key.toString() + " Value:"+eMap.get(key)); } } }