April 16, 2016
Java Generic Cache Implementation
Problem
Given the cache interface below
1 2 3 4 5 6 |
//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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//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); } } |