Difference between HashMap, LinkedHashMap and TreeMap

后端 未结 17 2117
醉话见心
醉话见心 2020-11-22 01:01

What is the difference between HashMap, LinkedHashMap and TreeMap in Java? I don\'t see any difference in the output as all the three

17条回答
  •  清酒与你
    2020-11-22 01:32

    HashMap
    can contain one null key.

    HashMap maintains no order.

    TreeMap

    TreeMap can not contain any null key.

    TreeMap maintains ascending order.

    LinkedHashMap

    LinkedHashMap can be used to maintain insertion order, on which keys are inserted into Map or it can also be used to maintain an access order, on which keys are accessed.

    Examples::

    1) HashMap map = new HashMap();

        map.put(null, "Kamran");
        map.put(2, "Ali");
        map.put(5, "From");
        map.put(4, "Dir");`enter code here`
        map.put(3, "Lower");
        for (Map.Entry m : map.entrySet()) {
            System.out.println(m.getKey() + "  " + m.getValue());
        } 
    

    2) TreeMap map = new TreeMap();

        map.put(1, "Kamran");
        map.put(2, "Ali");
        map.put(5, "From");
        map.put(4, "Dir");
        map.put(3, "Lower");
        for (Map.Entry m : map.entrySet()) {
            System.out.println(m.getKey() + "  " + m.getValue());
        }
    

    3) LinkedHashMap map = new LinkedHashMap();

        map.put(1, "Kamran");
        map.put(2, "Ali");
        map.put(5, "From");
        map.put(4, "Dir");
        map.put(3, "Lower");
        for (Map.Entry m : map.entrySet()) {
            System.out.println(m.getKey() + "  " + m.getValue());
        }
    

提交回复
热议问题