Преглед изворни кода

:sparkles: 优化 tree 泛型

如梦技术 пре 6 година
родитељ
комит
a9dcbaacec

+ 36 - 31
blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeManager.java

@@ -23,40 +23,45 @@ import java.util.List;
  *
  * @author zhuangqian
  */
-public class ForestNodeManager {
+public class ForestNodeManager<T extends INode> {
 
-    private List<INode> list;// 森林的所有节点
+	/**
+	 * 森林的所有节点
+	 */
+	private List<T> list;
 
-    public ForestNodeManager(List<INode> items) {
-        list = items;
-    }
+	public ForestNodeManager(List<T> items) {
+		list = items;
+	}
 
-    /**
-     * 根据节点ID获取一个节点
-     *
-     * @param id 节点ID
-     * @return 对应的节点对象
-     */
-    public INode getTreeNodeAT(int id) {
-        for (INode forestNode : list) {
-            if (forestNode.getId() == id)
-                return forestNode;
-        }
-        return null;
-    }
+	/**
+	 * 根据节点ID获取一个节点
+	 *
+	 * @param id 节点ID
+	 * @return 对应的节点对象
+	 */
+	public INode getTreeNodeAT(int id) {
+		for (INode forestNode : list) {
+			if (forestNode.getId() == id) {
+				return forestNode;
+			}
+		}
+		return null;
+	}
 
-    /**
-     * 获取树的根节点(一个森林对应多颗树)
-     *
-     * @return 树的根节点集合
-     */
-    public List<INode> getRoot() {
-        List<INode> roots = new ArrayList<>();
-        for (INode forestNode : list) {
-            if (forestNode.getParentId() == 0)
-                roots.add(forestNode);
-        }
-        return roots;
-    }
+	/**
+	 * 获取树的根节点(一个森林对应多颗树)
+	 *
+	 * @return 树的根节点集合
+	 */
+	public List<T> getRoot() {
+		List<T> roots = new ArrayList<>();
+		for (T forestNode : list) {
+			if (forestNode.getParentId() == 0) {
+				roots.add(forestNode);
+			}
+		}
+		return roots;
+	}
 
 }

+ 16 - 16
blade-core-tool/src/main/java/org/springblade/core/tool/node/ForestNodeMerger.java

@@ -24,22 +24,22 @@ import java.util.List;
  */
 public class ForestNodeMerger {
 
-    /**
-     * 将节点数组归并为一个森林(多棵树)(填充节点的children域)
-     * 时间复杂度为O(n^2)
-     *
-     * @param items 节点域
-     * @return 多棵树的根节点集合
-     */
-    public static List<INode> merge(List<INode> items) {
-        ForestNodeManager forestNodeManager = new ForestNodeManager(items);
-        for (INode forestNode : items) {
-            if (forestNode.getParentId() != 0) {
-                INode node = forestNodeManager.getTreeNodeAT(forestNode.getParentId());
+	/**
+	 * 将节点数组归并为一个森林(多棵树)(填充节点的children域)
+	 * 时间复杂度为O(n^2)
+	 *
+	 * @param items 节点域
+	 * @return 多棵树的根节点集合
+	 */
+	public static <T extends INode> List<T> merge(List<T> items) {
+		ForestNodeManager<T> forestNodeManager = new ForestNodeManager<>(items);
+		for (T forestNode : items) {
+			if (forestNode.getParentId() != 0) {
+				INode node = forestNodeManager.getTreeNodeAT(forestNode.getParentId());
 				node.getChildren().add(forestNode);
-            }
-        }
-        return forestNodeManager.getRoot();
-    }
+			}
+		}
+		return forestNodeManager.getRoot();
+	}
 
 }