java.util.LinkedHashMap.removeEldestEntry() method instance

The java.util.LinkedHashMap.removeEldestEntry()  method returns true if this map removes its oldest entry. This method is called after inserting a new entry into the map via put and putAll. It provides the implementer the opportunity to add a new one, removing the oldest entry each time. This is useful if the map represents a cache: it allows the map to reduce memory consumption by removing old entries.

 

statement

 

Following is the declaration of java.util.LinkedHashMap.removeEldestEntry() method

 

protectedboolean removeEldestEntry(Map.Entry<K,V> eldest)

 

parameter

 

  • eldest – the least recently inserted entry in the map, or if this is an access sequence graph, the least recently accessed entry. This will be removed, this method returns true. If the map was a previous put or call to putAll caused this call to be empty, this will be the entry that was just inserted; in other words, if the map contains an entry, the entry eldest is also up-to-date.

 

return value

 

This method returns true if the old entry is removed from the map; if it should be preserved.

 

abnormal

 

  • NA

 

example

 

The following example demonstrates the usage of the java.util.LinkedHashMap.removeEldestEntry() method.

 

package com.yiibai;import java.util.*;publicclassLinkedHashMapDemo{privatestaticfinalint MAX_ENTRIES =5;publicstaticvoid main(String[] args){LinkedHashMap lhm =newLinkedHashMap(MAX_ENTRIES +1,.75F,false){protectedboolean removeEldestEntry(Map.Entry eldest){return size()> MAX_ENTRIES;}};
      lhm.put(0,"H");
      lhm.put(1,"E");
      lhm.put(2,"L");
      lhm.put(3,"L");
      lhm.put(4,"O");System.out.println(""+ lhm);}}

 

Let's compile and run the above program, which will produce the following results:

 

{ 1 = E , 2 = L , 3 = L , 4 = O }



http://www.yiibai.com/java/util/linkedhashmap_removeeldestentry.html
http://blog.csdn.net/wangshione/article/details/6700985

http://www.yiibai.com/java/util/linkedhashmap_removeeldestentry.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327033323&siteId=291194637