Skip to content

Instantly share code, notes, and snippets.

@cakoose
Created May 16, 2018 22:31
Show Gist options
  • Save cakoose/39b13ab9b323b0573f55638c3dc6baec to your computer and use it in GitHub Desktop.
Save cakoose/39b13ab9b323b0573f55638c3dc6baec to your computer and use it in GitHub Desktop.
Type-safe heterogeneous map in Java
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);
}
}
@inkarnadin
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment