2012-01-27 136 views
2

我有一個應用程序需要使用GWT在網站的報告屏幕上顯示數據。這些信息需要按樹結構分組,樹的每一層都是不同類型的分組。Java:使用java創建樹結構的問題泛型

例如,數據可能需要按日期分組,然後按地區分組,然後按車輛分組。然而,在另一個類似的報告中,數據可能需要按照不同的順序分組,例如車輛,日期,地區。

因此,我使用泛型創建了一個樹結構,每種類型的分組都是樹節點的子類。下面是一個簡單的代碼版本。

public abstract class Node extends Composite implements Comparable<Node> 
{ 
    //sorts the subtree of this node using the comparable interface 
    //and by calling each of the child nodes sort methods 
    public abstract sort(); 

    //when called will draw this node and its entire subtree to the UI 
    //again by calling the child nodes draw method. 
    protected abstract draw(); 
} 

public abstract class ParentNode<E extends Node> extends Node 
{ 
    private List<E> children = new ArrayList<E>(); 

    public void addChild(E child) 
    { 
     children.add(child); 
    } 

    public List<E> getChildren() 
    { 
     return children; 
    } 

    public void sort() 
    { 
     Collections.sort(children) 

     for(E child : children) 
     child.sort(); 
    } 
} 

public class DateGrouping<E> extends ParentNode<Node> 
{ 
    public void draw() 
    { ... } 
} 

public class Data extends Node 
{...} 

public class Report 
{ 
    private RootNode<DateGrouping<RegionGrouping<VehicleGrouping<Data>>>> rootNode; 

    public Report() 
    { 
     rootNode = new RootNode<DateGrouping<RegionGrouping<VehicleGrouping<Data>>>>(); 
    } 
} 

注:其他組類型中相同的方式定義爲DateGrouping

的主要問題我與該實現的是,在上面的例子中調用

rootNode.getChildren() 

返回

List<Node> object 

不是

List<DateGrouping<RegionGrouping<VehicleGrouping<Data>>>> 

這意味着我必須做一堆髒鑄造才能使用返回的對象。

有沒有辦法避免做鑄造,或者更好的方式來編碼我的樹,所以我不必擔心它?

+1

奇怪,在我的情況(jdk1.7.0_01)'rootNode.getChildren()'正確返回'名單 >>>'。你使用什麼Java版本? – 2012-01-27 04:55:32

+0

我正在使用的項目仍在使用1.6 – OrangeSloth 2012-01-29 03:53:04

回答

0

首先,您還沒有向我們展示RootNode類的實現。 但是,如果您以與DateGrouping相同的方式實施,那麼行爲是正確的。仔細觀察你如何在DateGrouping

公共類DateGrouping < é>實現接口擴展ParentNode < 節點>

你不類型參數E.傳遞到ParentNode。所以getChildren()將返回List<Node>,不List<E>

+0

這看起來像是問題所在。應該是 public class DateGrouping extends ParentNode 我會在星期一回來工作時測試這個。謝謝。 – OrangeSloth 2012-01-29 03:53:36