Gaea Times Micro Blog

angsuman

  • 09:26:08 am on August 27, 2010 | # |

    The worst part about LinkedHashMap is the documentation (javadoc) and the name. While it implements a LinkedList in addition to a HashMap, its real use is to create a bounded set of HashMap entries where it is bounded by either eliminating the eldest entry in terms of when it was created or when it was last accessed. Check the last contructor to see how you can set the accessOrder to true to enable removing entries based on last access.

    Here is a simple example to help you understand how to use LinkedHashMap. Check the tests using assert carefully.

    
    import java.util.*;
    
    public class LinkedHashMapTest {
        public static void main(String args[]) {
            final int MAX_ENTRIES = 100;
            LinkedHashMap m = new LinkedHashMap() {
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    return size() > MAX_ENTRIES;
                }
            };
    
            // Test code
            for(int i = 1; i < = 200; i++) m.put(i, i);
            assert m.size() == MAX_ENTRIES;
            for(int i = 1; i <= 100; i++) assert m.get(i) == null;
            for(int i = 1; i <= 100; i++) assert m.get(i + 100) != null;
        }
    }
    
    
     

Leave a Comment

You must be logged in to post a comment.