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.
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
.
LinkedHashMap :- LinkedHashMap
It preserves your Insertion Order. and keys
will be found as same order you Insert into this LinkedHashMap
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With