Java Generic Cache Implementation

Problem

Given the cache interface below

//Generic Cache Interface
 public interface Cache<K, V> 
 {
	 public void put(K key, V value);
	 public V get(K key);
 }

We want to implement a generic cache class in order to improve compile time type checking.

Solution

Using Java Generics one can provide variable types as parameters for compile time type checking. In this case we are going to use K for key and V for value as follows

//Cache using Java Generics
public static class GenericCache<K, V> implements Cache<K, V> 
{
	 //Generic map
	 private Map<K, V> map;
	 
	 //Constructor
	 public GenericCache() 
	 {
		 map = new HashMap<K, V>();
	 }

	 //Generic method
	 public void put(K key, V value) 
	 {
		 map.put(key, value);
	 }

	 //Generic method
	 public V get(K key) 
	 {
		 return map.get(key);
	 }
}
Search Terms...

Leave a Reply

%d bloggers like this: