Image

Java - Core Java - Collection Framework - Map (I)

Map

  • Map is not a child interface of Collection.
  • If we want to represent a group of objects as a key-value pair then we should go for Map.
  • Both keys and values are object.
  • Only duplicate keys are not allowed but values can be duplicated.
  • Each (key, value) pair is called entry. Hence Map is considered as a collection of entry objects.
  • HashMap

  • The underlying Data Structure is Hashtable.
  • Insertion order is not preserved and it is based on hashcode of keys.
  • Duplicate keys are not allowed but values can be duplicated.
  • Heterogeneous objects are allowed for both keys and values.
  • Null is allowed for key (only once), null is allowed for values (any number of times).
  • Hashmap implements Serializable and Cloneable interface but not RandomAccess.
  • Hashmap is the best choice if our frequent operation is search operation.
  • Program
    import java.util.*;
    public class HashMapDemo2 {
        public static void main(String[] args) {
            HashMap hm=new HashMap();
            hm.put(100, "Amit");
            hm.put(101, "Vijay");
            hm.put(102, "Rahul");
            for (Map.Entry m : hm.entrySet()) {
                System.out.println(m.getKey()+" "+m.getValue());            
            }
        }
    }
    O/P
    100 Amit
    101 Vijay
    102 Rahul
    
    Difference between HashMap and Hashtable
    1567186461-image.png
    Difference between HashMap and LinkedHashMap
    1567186647-image.png

    LinkedHashMap

    It is a child class of HashMap. Fairly same as HashMap ( including methods and constructors) except above differences.

    LinkedHashSet and LinkedHashMap are commonly used for developing cache based application.

    Integer I1=new Integer(10);
    Integer I2=new Integer(10);
    Sop(I1==I2)   //false
    Sop(I1.equals(I2))  //true
    Note:- Difference == operator and .equals()

    In general == meant for reference comparison (address comparison) whereas equals () meant for content comparison.

    Program
    import java.util.*;
    public class LinkedHashMapDemo {
        public static void main(String[] args) {
            LinkedHashMap hm=new LinkedHashMap();
            hm.put(100, "Amit");
            hm.put(101, "Vijay");
            hm.put(102, "Rahul");
            for (Map.Entry m : hm.entrySet()) {
                System.out.println(m.getKey()+" "+m.getValue());
            }
        }
    }
    O/P
    100 Amit
    101 Vijay
    102 Rahul