Created
April 21, 2017 22:23
-
-
Save schmohlio/1a861d914b7a2582b69e2ee91af04ac3 to your computer and use it in GitHub Desktop.
Variable Depth Java HashMap
This file contains hidden or 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
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