Created
May 16, 2018 22:31
-
-
Save cakoose/39b13ab9b323b0573f55638c3dc6baec to your computer and use it in GitHub Desktop.
Type-safe heterogeneous map in Java
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
import java.util.IdentityHashMap; | |
public class HMap { | |
public static final class Key<T> {} | |
private IdentityHashMap<Key<?>, Object> inner = new IdentityHashMap<>(); | |
public <T> T get(Key<T> key) { | |
Object raw = inner.get(key); | |
@SuppressWarnings("unchecked") | |
T typed = (T) raw; | |
return typed; | |
} | |
public <T> void put(Key<T> key, T value) { | |
inner.put(key, value); | |
} | |
// Example usage: | |
private static final HMap.Key<String> NAME = new HMap.Key<>(); | |
private static final HMap.Key<Integer> AGE = new HMap.Key<>(); | |
public static void main(String[] args) { | |
HMap m = new HMap(); | |
m.put(NAME, "Turd Ferguson"); | |
m.put(AGE, 50); | |
String name = m.get(NAME); | |
Integer age = m.get(AGE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!