Skip to content

Instantly share code, notes, and snippets.

@schmohlio
Created April 21, 2017 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmohlio/1a861d914b7a2582b69e2ee91af04ac3 to your computer and use it in GitHub Desktop.
Save schmohlio/1a861d914b7a2582b69e2ee91af04ac3 to your computer and use it in GitHub Desktop.
Variable Depth Java HashMap
class NestedMap<K, V> {
private final HashMap<K, NestedMap> child;
private V value;
public NestedMap() {
child = new HashMap<>();
value = null;
}
public boolean hasChild(K k) {
return this.child.containsKey(k);
}
public NestedMap<K, V> getChild(K k) {
return this.child.get(k);
}
public void makeChild(K k) {
this.child.put(k, new NestedMap());
}
public V getValue() {
return value;
}
public void setValue(V v) {
value = v;
}
// EXAMPLE:
public static void main(String[] args) {
NestedMap<Character, String> m = new NestedMap<>();
m.makeChild('f');
m.getChild('f').makeChild('o');
m.getChild('f').getChild('o').makeChild('o');
m.getChild('f').getChild('o').getChild('o').setValue("bar");
System.out.println(
"nested element at 'f' -> 'o' -> 'o' is " +
m.getChild('f').getChild('o').getChild('o').getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment