我有一个Foo
对象,其中有一个引用Bar
个对象列表的字段。 Bar
列表中的每个Bar
对象都引用下一个Foo
对象。我们的想法是拥有一个Foo
个对象列表,每个对象都有一个Bar
列表,指向列表中不同的Foo
个对象(即foo1
指向foo2
{1}}和foo5
)。最后一个Foo
对象指向null
。在下面的示例中,有两个Foo
个实例:foo1
指向foo2
,foo2
指向null
。
如果我想构建一个链接的Foo
对象列表,我必须从最后一个对象开始并反向构建它。我可以递归地做这件事吗?
public class Foo {
private final String id;
private final List<Bar> barList;
public Foo(String id, List<Bar> barList) {
this.id = id;
this.barList = barList;
}
public String getId() {
return id;
}
public List<Bar> getBarList() {
return barList;
}
}
public class Bar {
private final Foo nextFoo;
public Bar(Foo nextFoo) {
this.nextFoo = nextFoo;
}
public Foo getNextFoo() {
return nextFoo;
}
}
public class FooListBuilder {
public static void main(String[] args) {
buildFoosInReverse();
// buildFoosRecursively();
}
public static void buildFoosInReverse() {
List<Foo> fooList = new ArrayList<Foo>();
Bar bar2 = new Bar(null);
List<Bar> bar2List = new ArrayList<Bar>();
bar2List.add(bar2);
Foo foo2 = new Foo("2", bar2List);
Bar bar1 = new Bar(foo2);
List<Bar> bar1List = new ArrayList<Bar>();
bar1List.add(bar1);
Foo foo1 = new Foo("1", bar1List);
fooList.add(foo1);
fooList.add(foo2);
System.out.println(fooList);
}
}
答案 0 :(得分:1)
首先,代码中的fooList
使用的是ArrayList
,LinkedList
不是LinkedList
,如果您希望LinkedList
可以使用现有的实现:{{3} }。
您可以使用以下内容从ArrayList
创建List<Foo> myLinkedList = new LinkedList<Foo>( fooList );
x_0 y_0 1
A = x_1 y_1 1
...
x_n y_n 1
现在回到你的问题,我不知道你怎么能&#34;构建&#34;使用递归的链接列表。
递归有助于解决打印链表等问题 - 即链表已存在时。
如果要构建链接列表,则需要按顺序调用LinkedList
。
答案 1 :(得分:1)
所以这有点棘手,因为你需要弄清楚什么时候需要实例化,并跟踪什么引用什么。诀窍是你需要在兔子洞里建造你的Foos,然后在回来的路上添加吧。
这是执行此操作的递归代码。
public static List<Foo> buildFoosRecursive(String[] values) {
ArrayList<Foo> list = new ArrayList<Foo>(values.length);
buildFoosRecursive(values, 0, list);
return list;
}
private static void buildFoosRecursive(String[] values, int index, List<Foo> fooList) {
if (index >= values.length)
return;
List<Bar> bar1List = new ArrayList<Bar>(1);
Foo newFoo = new Foo(values[index], bar1List);
fooList.add(newFoo);
buildFoosRecursive(values, index + 1, fooList);
Bar bar1;
if (fooList.size() > index + 1)
bar1 = new Bar(fooList.get(index + 1));
else
bar1 = new Bar(null);
bar1List.add(bar1);
return;
}