What is LinkedHashMap and what is it used for?
When I was going through the sample code with ListViews I came up with LinkedHashMap
. What is LinkedHashMap
and where can we use it and how? I have looked through several articles but did not fully understand. This is required when creating ListView
. What is the relationship between ListViews and LinkedHashMaps? Thank.
For simplicity, let's figure out what is the difference between HashMap and LinkedHashMap .
HashMap : it gives the result in random orders, means there is no correct sequence for how we inserted the values.
then
LinkedHashMap . It gives the result in sequential order.
Let's look at a small example: with HashMap
// suppose we have written a program
.
.
// now use HashMap
HashMap map = new HashMap(); // create object
map.put(1,"Rohit"); // insert values
map.put(2,"Rahul");
map.put(3,"Ajay");
System.out.println("MAP=" +map); //print the output using concatenation
//So the output may be in any order like we can say the output may be as:
Map={3=Ajay,2=Rahul,1=Rohit}
but this is not the case in LinkedHashMap Just replace "HashMap" with "LinkedHashMap" in the above code and see it displays the output in sequential order, eg 1 = Rohit will be displayed first and then the rest.
The docs are here. But it's basically a HashMap that also has a linked list, so you can have a sequentially ordered iteration through it. Note that this means deletion can be O (n) time because you need to delete it from both data structures.
LinkedHashMap - hashmap. But it maintains the insertion order. But HashMap doesn't maintain order.
Hi Linked Hash Map is a map that stores a pair of key values, A Linked Hash Map adds values ββwhich can be very slow but very easy when retrieving the values. For quick retrieval of values, we may prefer Linked Hash Map.