views:

70

answers:

2

Hi, i know that the LinkedHashMap provides a constructor, where you can indicate if the map should be sorted by the access order thus effectively providing an LRU implementation. Can you tell me which (and if) other Collections and Maps from the big Collections zoo provide this feature?

+1  A: 

I don't think any such Collections or Maps exist (but I also heard of that constructor for the first time just now). I have checked Guava, but I don't think they have a solution, either.

But I think it could be easily achieved using the decorator pattern. Write a delegate object that implements the interface you want and delegates all methods to an inner object. Your wrapper also contains a LinkedHashSet / LinkedHashMap (depending on whether you are dealing with a collection or map) that logs data access.

Now your iterator() / entrySet() methods provide a view that's backed first by the LinkedHashSet/Map and then by the rest of the data (or vice-versa if you want to reverse the access order).

I would implement it using wrapper methods like the ones in the Collections class.

E.g.

Map<String,String> map = CollectionUtils.viewMapByAccessOrder(
                             new HashMap<String,String>());
List<String> list = CollectionUtils.viewListByAccessOrder(
                             new ArrayList<String>());

This could actually be functionality that makes sense for a larger audience. I'd consider filing a feature request in the Guava project.

seanizer
that would work, thank you. maybe i should have asked for LRU implemetantions other than the LinkedHashMap in the first place :)
kostja
+2  A: 

I don't think I completely understand the question, but maybe you want to have a look in the LRUMap implementation of the Commons Collections framework.

DouglasJose
very cool, i wasnt aware of that one, thank you
kostja