Skip to content

Instantly share code, notes, and snippets.

@andrewrlee
Created July 3, 2016 20:18
Show Gist options
  • Save andrewrlee/c386f11e184ac78ea3077bee5fa7b554 to your computer and use it in GitHub Desktop.
Save andrewrlee/c386f11e184ac78ea3077bee5fa7b554 to your computer and use it in GitHub Desktop.
package uk.co.optimisticpanda.test;
import java.util.HashMap;
import java.util.Map;
/**
* Supporting subset of map operations based on the key containing type information.
*/
public class TypeSafeMapTest {
public static class Key<T> {
private final String key;
public Key(String key) {
this.key = key;
}
@SuppressWarnings("unchecked")
public T get(Map<?, ?> map) {
return (T) map.get(key);
}
@SuppressWarnings("unchecked")
public T put(Map<? super Object, ? super Object> map, T value) {
return (T) map.put(key, value);
}
@SuppressWarnings("unchecked")
public T remove(Map<? super Object, ? super Object> map) {
return (T) map.remove(key);
}
}
public static class TypeSafeMap {
private final Map<Object, Object> map = new HashMap<Object, Object>();
public <T, A extends Key<T>> T get(A key) {
return key.get(map);
}
public <T, A extends Key<T>> T put(A key, T value) {
return key.put(map, value);
}
public <T, A extends Key<T>> T remove(A key) {
return key.remove(map);
}
}
public static void main(String[] args) {
Key<String> NAME = new Key<>("name");
Key<Long> AGE = new Key<>("age");
TypeSafeMap safeMap = new TypeSafeMap();
safeMap.put(NAME, "Andrew");
safeMap.put(AGE, 234L);
String name = safeMap.get(NAME);
Long age = safeMap.get(AGE);
System.out.println(name + ", " + age);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment