Both EnumMaps and HashMaps are part of the Java.util package, and they implement the Map Interfaces and access its methods. Specifically, EnumMaps implements the map interface associated with enumeration types. HashMaps, on the other hand, are widely used in the implementation of hashtables.
Let's take a look at what makes Hashmaps and EnumMaps different in Java
Here are the three most common differences between the EnumMaps and HashMaps
In general, the two types of implementation differ in their purposes. EnumMaps are designed for enumeration keys, whereas HashMaps are designed for hashtables.
The performance between the two differs. As a result of the specialised optimization done for Enum keys, they are more likely to perform better when used as the key object than the HashMap.
Finally, HashMap and EnumMap differ in the probability of collision. This is because the Enum is internally maintained as an array and is sorted by order with ordinal().
import java.util.EnumMap; import java.util.HashMap; import java.util.Map;
public class EnumMaps_HashMaps { public enum Planguages { Python, Java, Kotlin, Rubby; } public static void main(String[] args) { EnumMap<Planguages, Integer> enumMap = new EnumMap<>(Planguages.class); enumMap.put(Planguages.Python, 1); enumMap.put(Planguages.Java, 2); enumMap.put(Planguages.Kotlin, 3); enumMap.put(Planguages.Rubby, 4); System.out.println("Our EnumMap: " + enumMap.size()); for (Map.Entry m : enumMap.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } // HashMap HashMap<Integer, String> mymap = new HashMap<>(); mymap.put(1, "Python"); mymap.put(2, "Java"); mymap.put(3, "Rubby"); System.out.println("Our map is: " + mymap.size()); for (Map.Entry a : mymap.entrySet()) { System.out.println(a.getKey() + " " + a.getValue()); } } } |
Output
Our EnumMap: 4 Python 1 Java 2 Kotlin 3 Rubby 4 Our map is: 3 1 Python 2 Java 3 Rubby |
Keywords: EnumMaps, HashMaps
Article Contributed By :
|
|
|
|
101 Views |