工作中碰到了树形结构的一些需求
- 提供节点为null值的存储
- 提供父节点的引用,且更新子节点时父节点所持有的子节点引用同步更新
- 提供查询当前节点所处高度,父节点所处高度
- 即时挂载父节点,更改父节点时,同步更新父节点的父节点引用信息,以及父节点的子节点引用信息
- 类似双向链表,对父项和子项信息的同步更新进行null值考虑,并对多线程操作时考虑一些节点拥有的属性的并发安全性问题
- 后续有需要会更新优化,如果有写的欠缺的地方,请读者在评论处指出
package com.xxxx;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.util.CollectionUtils;
public class CommonNode {
private T data;
private CommonNode parentNode;
private AtomicInteger currentNodeHeight;
private AtomicInteger parentNodeHeight;
private List> childCommonNodes;
private CommonNode() {
}
public CommonNode(final T data) {
if (data != null) {
this.setData(data);
}
this.currentNodeHeight = new AtomicInteger(0);
this.parentNodeHeight = new AtomicInteger(-1);
}
public CommonNode(final T data, final CommonNode parentNode) {
if (data != null) {
this.setData(data);
}
if (parentNode != null) {
this.setParentNode(parentNode);
} else {
this.currentNodeHeight = new AtomicInteger(0);
this.parentNodeHeight = new AtomicInteger(-1);
}
}
public void setData(final T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setParentNode(final CommonNode parentNode) {
// 之前连接的如果有父节点,需要把父节点中持有的引用删掉
CommonNode beforeAddParentNode = this.getParentNode();
if (beforeAddParentNode != null) {
List> beforeAddChildCommonNodes = beforeAddParentNode.getChildCommonNodes();
if (!CollectionUtils.isEmpty(beforeAddChildCommonNodes)) {
beforeAddChildCommonNodes.remove(this);
}
} else {
List> curCommonNodes = parentNode.getChildCommonNodes();
if (curCommonNodes == null) {
curCommonNodes = new CopyOnWriteArrayList<>();
parentNode.setChildCommonNodes(curCommonNodes);
}
curCommonNodes.add(this);
}
this.parentNode = parentNode;
this.parentNodeHeight = parentNode.getCurrentNodeHeight();
this.currentNodeHeight = new AtomicInteger(parentNode.getCurrentNodeHeight().get()+1);
}
public AtomicInteger getCurrentNodeHeight() {
return currentNodeHeight;
}
private void setCurrentNodeHeight(final AtomicInteger newCurrentNodeHeight) {
currentNodeHeight = newCurrentNodeHeight;
}
public CommonNode getParentNode() {
return parentNode;
}
public AtomicInteger getParentNodeHeight() {
return parentNodeHeight;
}
private void setParentNodeHeight(final AtomicInteger newParentNodeHeight) {
parentNodeHeight = newParentNodeHeight;
}
public List> getChildCommonNodes() {
return childCommonNodes;
}
public void setChildCommonNodes(final List> newChildCommonNodes) {
childCommonNodes = newChildCommonNodes;
}
}