LinkedHashMap Class
In this chapter you will learn:
Use LinkedHashMap
LinkedHashMap
extends HashMap
.
It maintains a linked list of the entries in the map, in the order in which they were inserted.
This allows insertion-order iteration over the map.
LinkedHashMap
is a generic class that has this declaration:
class LinkedHashMap<K, V>
K
specifies the type of keysV
specifies the type of values.
LinkedHashMap
adds only one method to those defined by HashMap
.
This method is removeEldestEntry( ) and it is shown here:
protected boolean removeEldestEntry(Map.Entry<K, V> e)
This method is called by put( )
and putAll( )
.
The oldest entry is passed in e
.
import java.util.LinkedHashMap;
/*j a v a 2 s . com*/
public class Main {
public static void main(String[] args) {
LinkedHashMap<Integer, Integer> linkedMap = new LinkedHashMap<Integer, Integer>();
for (int i = 0; i < 10; i++) {
linkedMap.put(i, i);
}
System.out.println(linkedMap);
// Least-recently used order:
linkedMap = new LinkedHashMap<Integer, Integer>(16, 0.75f, true);
for (int i = 0; i < 10; i++) {
linkedMap.put(i, i);
}
System.out.println(linkedMap);
for (int i = 0; i < 7; i++)
System.out.println(linkedMap.get(i));
System.out.println(linkedMap);
}
}
The code above generates the following result.
{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}
{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}
0/* ja va2s. co m*/
1
2
3
4
5
6
{7=7, 8=8, 9=9, 0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections