我有所有叶子都有索引的树,当树以数据库的形式递归时,数据库将通过索引对树进行排序。首先,它获取按索引排序的根节点,依此类推。现在我需要实现操作,用户可以通过按向上/向下箭头图标对这些索引进行排序。当用户按下时,索引应该采用它自己索引下的索引,当按下向上箭头时,反之亦然。我只是不知道实现这种功能的最佳方法是什么。
答案 0 :(得分:1)
由于你的问题有点模糊,这个答案假设你知道你在做数据库时你在做什么(如果没有,我会推荐hibernate for java)以下代码是为了给你一些实现的想法你的解决方案。
//If I have understood your question, you want two nodes to swap position in the tree structure
public static swapNode(Node parent, Node child)
{
Long superId = parent.getParentId();
child.parentId(superId);
parent.setParentId(child.getId());
child.setId(parentId);
//update children lists of parent and child
//update parent ids of children lists
//save changes to database
}
//create tree structure from database. Assumes nodes have been loaded from a database
//table where each row represents a node with a parent id column the root node which has parent id null)
//invoke this with all nodes and null for parentId argument
public static List<Node> createNodeTree(List<Node> allNodes, Long parentId)
{
List<Node> treeList = new ArrayList<Node>();
for(Node node : nodes)
{
if(parentIdMatches(node, parentId))
{
node.setChildren(createNodeTree(allNodes, node.getId()));
treeList.add(node);
}
}
return treeList;
}
private static boolean parentIdMatches(Node node, Long parentId)
{
return (parentId != null && parentId.equals(node.getParentId()))
|| (parentId == null && node.getParentId() == null);
}
//The objects loaded from the database should implement this interface
public interface Node
{
void setParentId(Long id);
Long getParentId();
Long getId();
List<Node> getChildren();
void setChildren(List<Node> nodes);
}