Map and HashMap difference
Difference
- Map is an interface but HashMap is a class. So you cannot create an object of a Map but you can create an object of a HashMap
Map <String, Integer> empIds = new Map<>(); // This will give a compile time error
Map <String, Integer> empIds = new HashMap<>(); // This is allowed
- Map contains unique key value pairs but HashMap can have duplicate values.
- Map interface can be implemented by using its implementing class. Whereas HashMap class implements the Map interface.
- Map is used to create, Hashmap and TreeMap. While HashMap implements Map interface and extends AbstractMap class.
- There is no difference between the objects of Map and HashMap. Both of them maintains an insertion order.
- You are not allowed to use primitive data types (int, float, double, char) to define a Map or a HashMap. You have to use non-primitive data types (Integer, Float, Double, Character, String, Objects) to define a Map or HashMap.
Example of Map
public class Maps {
public static void main(String[] args) {
Map <String, Integer> empIds = new HashMap<>();
empIds.put("Shirley", null);
empIds.put("Raaj", 24372);
empIds.put("Abhishek", 10082);
empIds.put("Rahul", 10032);
System.out.println(empIds);
System.out.println(empIds.get("Abhishek"));
System.out.println(empIds.containsKey("Ravi"));
System.out.println(empIds.containsValue(10032));
System.out.println(empIds.putIfAbsent("Raaj", 24373));
System.out.println(empIds.replace("", 24389));
empIds.remove("Rahul");
System.out.println(empIds);
}
}
Example of HashMap
public class Maps {
public static void main(String[] args) {
HashMap <String, Integer> empIds = new HashMap<>();
empIds.put("Shirley", null);
empIds.put("Raaj", 24372);
empIds.put("Abhishek", 10082);
empIds.put("Rahul", 10032);
System.out.println(empIds);
System.out.println(empIds.get("Abhishek"));
System.out.println(empIds.containsKey("Ravi"));
System.out.println(empIds.containsValue(10032));
System.out.println(empIds.putIfAbsent("Raaj", 24373));
System.out.println(empIds.replace("", 24389));
empIds.remove("Rahul");
System.out.println(empIds);
}
}
Comments
Post a Comment