用java实现php式的字典使用方式
sample:
array = {}
array["multi"]["dimensional"]["array"] = "hello"
echo array["multi"]["dimensional"]["array"]
NestedMap array = new NestedMap(); array.put("multi").put("dimensional").put("array").giveValue("hello");
System.out.println(array.get("multi").get("dimensional").get("array").getValue())
java code:
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class NestedMap<K,V> {
private V val;
private Map<K,NestedMap<K,V>> childs;
public NestedMap<K,V> put(K key) {
if(childs == null){
childs = new HashMap<>();
}
return childs.computeIfAbsent(key, k -> new NestedMap<>());
}
public void giveValue(V val){
this.val = val;
}
public V getValue(){
return Objects.requireNonNull(val,"lack of value");
}
public NestedMap<K,V> get(K key){
return childs.get(key);
}
public void clear(){
this.childs.clear();
}
public static void main(String[] args){
NestedMap<String,String> nestedMap = new NestedMap<>();
nestedMap.put("a").put("b").put("c");
nestedMap.put("a").giveValue("b");
nestedMap.put("a").put("c").giveValue("c");
nestedMap.put("e").put("b").giveValue("hello");
nestedMap.put("a").giveValue("hello");
nestedMap.put("e").put("a").giveValue("world");
nestedMap.giveValue("hello");
assert "hello".equals(nestedMap.getValue());
assert "world".equals( nestedMap.get("e").get("a").getValue());
}
}