Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of LinkedHashMap.removeEldestEntry?

I am aware the answer to this question is easily available on the internet. I need to know what happens if I choose not to removeEldestEntry. Below is my code:

package collection;

import java.util.*;

public class MyLinkedHashMap {

   private static final int MAX_ENTRIES = 2;

   public static void main(String[] args) {
      LinkedHashMap lhm = new LinkedHashMap(MAX_ENTRIES, 0.75F, false) {

         protected boolean removeEldestEntry(Map.Entry eldest) {
            return false;
         }
      };
      lhm.put(0, "H");
      lhm.put(1, "E");
      lhm.put(2, "L");
      lhm.put(3, "L");
      lhm.put(4, "O");

      System.out.println("" + lhm);

   }
}

Even though I am not allowing the removeEldestEntry my code works fine. So, internally what is happening?

like image 693
user1877246 Avatar asked Dec 25 '13 12:12

user1877246


People also ask

What is the use of LinkedHashMap?

Answer: The main use of LinkedHashMap in Java is to use it for preserving the insertion order. It can also be used to preserve the access order using which the keys are accessed.

How do you delete oldest entry in LinkedHashMap?

LinkedHashMap. removeEldestEntry() method returns true if this map should remove its eldest entry. This method is invoked by put and putAll after inserting a new entry into the map. It provides the implementor with the opportunity to remove the eldest entry each time a new one is added.

What is a LinkedHashMap?

A LinkedHashMap is a combination of hash table and linked list. It has a predictable iteration order (a la linked list), yet the retrieval speed is that of a HashMap. The order of the iteration is determined by the insertion order, so you will get the key/values back in the order that they were added to this Map.

What is difference between LinkedHashMap and HashMap?

The key difference between HashMap and LinkedHashMap is order. Elements of a HashMap are not in order, totally random, whereas elements of LinkedHashMap are ordered. The entries of a LinkedHashMap are in key insertion order, which is the order in which the keys are inserted in the Map.


4 Answers

removeEldestEntry always gets checked after an element was inserted. For example, if you override the method to always return true, the LinkedHashMap will always be empty, since after every put or putAll insertion, the eldest element will be removed, no matter what. The JavaDoc shows a very sensible example on how to use it:

protected boolean removeEldestEntry(Map.Entry eldest){
    return size() > MAX_SIZE;
}

In an alternative way, you might only want to remove an entry if it is unimportant:

protected boolean removeEldestEntry(Map.Entry eldest){
    if(size() > MAX_ENTRIES){
       if(isImportant(eldest)){
          //Handle an important entry here, like reinserting it to the back of the list
          this.remove(eldest.getKey());
          this.put(eldest.getKey(), eldest.getValue());
          //removeEldestEntry will be called again, now with the next entry
          //so the size should not exceed the MAX_ENTRIES value
          //WARNING: If every element is important, this will loop indefinetly!
       } else {
           return true; //Element is unimportant
       }
    return false; //Size not reached or eldest element was already handled otherwise
}
like image 151
salbeira Avatar answered Oct 02 '22 18:10

salbeira


Why can't people just answer the OP's simple question!

If removeEldestEntry returns false then no items will ever be removed from the map and it will essentially behave like a normal Map.

like image 25
David Newcomb Avatar answered Oct 02 '22 20:10

David Newcomb


Expanding on the answer by DavidNewcomb:

I'm assuming that you are learning how to implement a cache.

The method LinkedHashMap.removeEldestEntry is a method very commonly used in cache data structures, where the size of the cache is limited to a certain threshold. In such cases, the removeEldestEntry method can be set to automatically remove the oldest entry when the size exceeds the threshold (defined by the MAX_ENTRIES attribute) - as in the example provided here.

On the other hand, when you override the removeEldestEntry method this way, you are ensuring that nothing ever happens when the MAX_ENTRIES threshold is exceeded. In other words, the data structure would not behave like a cache, but rather a normal map.

like image 28
Arvindh Mani Avatar answered Oct 02 '22 19:10

Arvindh Mani


Your removeEldestEntry method is identical to the default implementation of LinkedHashMap.removeEldestEntry, so your LinkedHashMap will simply behave like a normal LinkedHashMap with no overridden methods, retaining whatever you values and keys put into it unless and until you explicitly remove them by calling remove, removeAll, clear, etc. The advantage of using LinkedHashMap is that the collection views (keySet(), values(), entrySet()) always return Iterators that traverse the keys and/or values in the order they were added to the Map.

like image 22
VGR Avatar answered Oct 02 '22 20:10

VGR