Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashmap put(), is it always ordering?

When we add values to hashmap<Key, Value> variable using put(), are they always ordering?

Because when I tried with simple codes they are ordering.

Example:

Map<Integer, Integer> ctrArMap = new HashMap<Integer, Integer>();
    ctrArMap.put( 1, 11);
    ctrArMap.put( 2, 12);
    ctrArMap.put( 3, 13);
    ctrArMap.put( 4, 14);
    ctrArMap.put( 5, 15);
    System.out.println(ctrArMap);

But in my case they aren't ordering.

like image 923
Pally Avatar asked Mar 16 '16 04:03

Pally


1 Answers

  1. HashMap :- HashMap never preserves your Insertion Order. It Internally Use a hashing Concept by which it generate a HashCode to the Corresponding key and add it to the HashMap.

  2. LinkedHashMap :- LinkedHashMap It preserves your Insertion Order. and keys will be found as same order you Insert into this LinkedHashMap.

  3. TreeMap :- The TreeMap class implements the Map interface by using a Tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.

You should note that, unlike a HashMap, a tree map guarantees that its elements will be sorted in ascending key order

like image 192
Vikrant Kashyap Avatar answered Sep 21 '22 21:09

Vikrant Kashyap