我有一棵树,我需要它看起来像这样
Head(T holds a string object)
/ \
1st child (T MyClass object) 2nd Child (T MyOtherClass object)
答案 0 :(得分:0)
您可以使用联合类型,a.k.a。Either
。以下是javaslang的实现:http://static.javadoc.io/io.javaslang/javaslang/2.0.2/javaslang/control/Either.html
这允许您拥有Tree<Either<A,B>>
,其中节点可以是A
或B
类型(包含在Either
中)。但是,这仅适用于两种类型。虽然您可以嵌套Either
s(例如Either<A, Either<B,C>>
三种类型),但这种方法显然无法很好地扩展。
答案 1 :(得分:0)
As the comment suggests from luk, if you're looking for a tree that's exactly as you've drawn out, you can have three generic type parameters in your class declaration.
class ThreeTree<U, V, W> {
private U root;
private V left;
private W right;
}
Unfortunately, this doesn't help you if you want a larger, more dynamic tree. One possible option you can explore in this case is using typesafe heterogenous containers. This wouldn't be much different from having a tree of Objects and casting them to the type you want when you want to get, but you will at least be able to accomplish the basic task of putting different types into the tree.
Take a look at Joshua Bloch's Effective Java, chapter 5 for some more thoughts on generics.