Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is LinkedHashMap and what is it used for?

When I was going through a example code which has ListViews I came up with LinkedHashMap. What is a LinkedHashMap and where can we use it and how? I went through several articles but did not understand fully. Is it necessary when creating ListView. What is the connection between ListViews and LinkedHashMaps? Thank you.

like image 823
CraZyDroiD Avatar asked Mar 18 '23 17:03

CraZyDroiD


2 Answers

For Simplicity, let us understand what is the difference between HashMap and LinkedHashMap.

HashMap: It gives output in Random orders means there is no proper sequence how we have inserted values.

whereas

LinkedHashMap: It gives output in sequential order.

Let us see 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 the "HashMap" with "LinkedHashMap" in the above code and see it will display the output in Sequential order like 1=Rohit will be displayed first then the others in sequence.

like image 133
Ashraf.Shk786 Avatar answered Mar 21 '23 07:03

Ashraf.Shk786


The docs are here. But its basically a HashMap that also has a linked list, so you can have a consistently ordered iteration through it. Note that this means removals may be O(n) time because you need to remove it from both data structures.

like image 29
Gabe Sechan Avatar answered Mar 21 '23 07:03

Gabe Sechan