package com.darcycasselman.cachedemo;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;

public class LruCacheImpl implements LruCache {

	private static int DEFAULT_CACHE_SIZE = 10;
	
	private Map<Object, Object> cache = new HashMap<>();
	private LinkedList<Object> recentOrderList = new LinkedList<>();
	
	private int maxSize;
	
	public LruCacheImpl(int maxSize) {
		this.maxSize = maxSize;
	}

	public LruCacheImpl() {
		this(DEFAULT_CACHE_SIZE);
	}

	@Override
	public Object get(Object key) {
		if ( !recentOrderList.remove(key) ) {
			return null;
		}
		recentOrderList.push(key);
		
		return cache.get(key);
	}

	@Override
	public void put(Object key, Object value) {
		recentOrderList.push(key);
		cache.put(key, value);
	}

	@Override
	public int getMaxSize() {
		return maxSize;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		
		ListIterator<Object> iterator = recentOrderList.listIterator();
		while ( iterator.hasNext() ) {
			Object key = iterator.next();
			sb.append(key);
			sb.append("=");
			sb.append(cache.get(key));
			if ( iterator.hasNext() ) {
				sb.append(", ");
			}
			
		}
		sb.append("}");
		
		return sb.toString();
	}
	
	

}

@@ -723,24 +723,156 @@
 ct value) %7B%0A
+%09%09if ( recentOrderList.size() %3E= maxSize ) %7B%0A%09%09%09Object oldestKey = recentOrderList.removeLast();%0A%09%09%09cache.remove(oldestKey);%0A%09%09%7D%0A%09%09%0A
 %09%09recentOrde

Remove oldest item from the cache when the cache is full.