Created
July 3, 2016 20:18
-
-
Save andrewrlee/c386f11e184ac78ea3077bee5fa7b554 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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