2010-11-22 16 views
0

私はすべてのリーフがインデックスを持っているツリーを持っています、ツリーがレスキューされたときにフォームデータベース、データベースはインデックスでツリーを並べます。まず、索引などでソートされたルートノードを取得します。今、私はどのようにユーザーが上下の矢印アイコンを押してこれらのインデックスをソートできるアクションを実装する必要があります。ユーザーが下を押すと、索引はその索引の下にある索引を取るべきであり、上矢印が押されたときにはその逆を行うべきである。私はこの種の機能を実装する最良の方法が何であるか分かりません。再帰的ツリーインデックスの順序?

+0

すべてのノードにインデックスまたは葉のみがありますか?インデックスの生成方法 –

+0

すべてのノードにインデックスがあり、すべてのノードが同じデータベーステーブルにあります。索引は、すべての索引の最高の索引として作成されます。 – newbie

答えて

1

あなたの質問は多少曖昧ですので、この回答は、あなたがデータベースのものについては何をしているのかを知っていると仮定しています(私は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); 
}