What is the use of LinkedHashMap.removeEldestEntry?

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
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)