【发布时间】:2014-08-16 17:05:28
【问题描述】:
确切地说,我正在尝试展平一棵树,但我一直在尝试使用泛型函数获取泛型类中私有属性的值。
我附上了这些类来展示树的结构是如何准确的。但它看起来像这样:
/|\
1 | 6
/|\
5 4 9
我将在最后粘贴我的尝试。首先,让我介绍一下这些类:
Triple 只是存储三个相同类型的值。
public class Triple<V> {
private final V l, m, r;
public Triple(V l, V m, V r) {
this.l = l;
this.m = m;
this.r = r;
}
public V left() { return l; }
public V middle() { return m; }
public V right() { return r; }
}
简单的界面:
public interface Function<P, R> {
R apply(P p);
}
现在,上一堂棘手的课。这只是一种存储两种类型值的 EitherOr 之一的类型,但不能同时存储两者。
public class EitherOr<A,B> {
// Constructs a left-type EitherOr
public static <A> EitherOr left(A a) {
return new EitherOr(a, null);
}
// Constructs a right-type EitherOr
public static <B> EitherOr right(B b) {
return new EitherOr(null, b);
}
private final A a;
private final B b;
private EitherOr(A a, B b) {
this.a = a; this.b = b;
}
public<T> T ifLeft(Function<A,T> f) {
return f.apply(a);
}
public<T> T ifRight(Function<B,T> f) {
return f.apply(b);
}
public boolean isLeft() {
return b == null;
}
}
我知道这会越来越长,但请耐心等待。这个类实现了树形结构。
public interface Tree<T> {
EitherOr<T, Triple<Tree<T>>> get();
static final class Leaf<T> implements Tree<T> {
public static <T> Leaf<T> leaf (T value) {
return new Leaf<T>(value);
}
private final T t;
public Leaf(T t) { this.t = t; }
@Override
public EitherOr<T, Triple<Tree<T>>> get() {
return EitherOr.left(t);
}
}
static final class Node<T> implements Tree<T> {
public static <T> Tree<T> tree (T left, T middle, T right) {
return new Node<T>(Leaf.leaf(left), Leaf.leaf(middle), Leaf.leaf(right));
}
private final Triple<Tree<T>> branches;
public Node(Tree<T> left, Tree<T> middle, Tree<T> right) {
this.branches = new Triple<Tree<T>>(left, middle, right);
}
@Override
public EitherOr<T, Triple<Tree<T>>> get() {
return EitherOr.right(branches);
}
}
}
好的。这是我的扁平化想法:
public class MyFlattenTree<T> implements FlattenTree<T> {
public List<T> flattenInOrder(Tree<T> tree) {
List<T> list = new ArrayList<T>();
EitherOr<T, Triple<Tree<T>>> EitherOr;
EitherOr = tree.get();
// it is a leaf
if (EitherOr.isLeft()) {
// This is where the problem lies
// I don't how to get the value using a function f
list.add((T) EitherOr.ifLeft(f));
return list;
}
else {
// basically recursively go through the tree somehow
}
return null;
}
}
正如我所说,我一直在尝试使用 Function 接口检索 EitherOr 类中的值。我正在考虑实现函数接口并为“应用”编写一个函数来获取值,但我不知道该怎么做。任何帮助,将不胜感激。谢谢!
【问题讨论】:
-
您在申请 Atlassian 的工作吗?
-
仅供参考,Guava 库为此提供了一个工具:
TreeTraverser。
标签: java oop generics interface tree-traversal