我有一个应用程序需要使用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>>>>
这意味着我必须做一堆脏铸造才能使用返回的对象。
有没有办法避免做铸造,或者更好的方式来编码我的树,所以我不必担心它?
奇怪,在我的情况(jdk1.7.0_01)'rootNode.getChildren()'正确返回'名单 >>>'。你使用什么Java版本? –
2012-01-27 04:55:32
我正在使用的项目仍在使用1.6 – OrangeSloth 2012-01-29 03:53:04