2021SC@SDUSC
前言
本节介绍PathTrie类的静态内部类TrieNode,即字典树的节点类
TrieNode
成员变量
//节点存储的值
final String value;
//Map,存储子节点的value到子节点的映射
final Map<String, TrieNode> children;
//property为true,当且仅当对应的路径(从根节点到该节点)存在
boolean property;
//节点的父节点
TrieNode parent;
构造函数:
//private构造函数,只对当前外部类开放
private TrieNode(TrieNode parent, String value) {
this.value = value;
this.parent = parent;
this.property = false;
//初始化容量为4,平衡内存消耗与哈希表的更新效率
this.children = new HashMap<>(4);
}
parent,property的get/set方法,value的get方法:
TrieNode getParent() {
return this.parent;
}
void setParent(TrieNode parent) {
this.parent = parent;
}
void setProperty(boolean prop) {
this.property = prop;
}
boolean hasProperty() {
return this.property;
}
public String getValue() {
return this.value;
}
addChild,deleteChild方法:
//事实上在zookeeper中调addChild前总会先判断hashmap中是否已有对应的key
//但该函数的实现依然是用了putIfAbsent来保证健壮性
void addChild(String childName, TrieNode node) {
this.children.putIfAbsent(childName, node);
}
void deleteChild(String childName) {
this.children.computeIfPresent(childName, (key, childNode) -> {
//删除一个子节点,首先子节点一定是propety设为false
childNode.setProperty(false);
//而子节点对象是否要删除,要取决于该子节点是否是叶子节点
//如果该子节点没有子节点,那么就可以直接在hashmap中删除它了
if (childNode.isLeafNode()) {
childNode.setParent(null);
return null;
}
return childNode;
});
}
getChild,getChildren方法:
//根据子节点存的值,来获取该节点的子节点
TrieNode getChild(String childName) {
return this.children.get(childName);
}
//获取该节点的子节点们存储的值集合
Collection<String> getChildren() {
return children.keySet();
}
isLeafNode方法:
//判断该节点是否是叶子节点,通过children是否为空(即该节点是否有子节点)
boolean isLeafNode() {
return children.isEmpty();
}