gpt4 book ai didi

java - 迭代 java.lang.Iterable 的数组或实例 - 缺少常识解决方案?

转载 作者:行者123 更新时间:2023-11-29 05:21:47 25 4
gpt4 key购买 nike

我正在尝试使用双向链表(称为 LinkedTree)实现树结构。话虽如此,当使用我的 for-each 循环时,我最终得到了相同的重复错误:Can only iterate over an array or an instance of java.lang.Iterable。我已经在网上查找了一些类似的问题,但我似乎无法找到问题所在。我知道为了迭代器,你必须有可迭代的实例,但 positions 和 children() 不是两个可迭代的实例吗?我已经将这两种方法都包含在错误中,我的子方法以及我自己的可迭代和迭代器实现。在此先感谢您的帮助。

public Iterator<E> iterator() {

Iterable<Position<E>> positions = positions();
PositionalList<E> elements = new NodePositionalList<E>();
for (Position<E> p: positions) // ERROR @ positions
elements.addLast(p.element());
return elements.iterator();

}

private void preOrderPositions(Position<E> v, PositionalList<Position<E>> pos)
throws InvalidPositionException {
pos.addLast(v);
for (Position<E> w : children(v)) //ERROR @ children (v)
preOrderPositions(w, pos);
}

子方法

public Iterable<Position<E>> children(Position<E> v)
throws InvalidPositionException {
TreePosition <E> p = checkPosition(v);

if (isExternal(v))
throw new InvalidPositionException("");
return p.getChildren();

迭代器

public interface Iterator<E> {

public boolean hasNext();

public E next();

public void remove();

}

可迭代

public interface Iterable <E> { 

public Iterator<E> iterator();

public Iterable<Position<E>> positions();

}

ElementIterator(我的迭代器实现)

public class ElementIterator<E> implements Iterator <E> {

private PositionalList <E> list;
private Position <E> cursor;

public ElementIterator (PositionalList <E> L){

list = L;
cursor = (list.isEmpty())? null: list.first();
}

public boolean hasNext() {
return (cursor != null);
}

public E next(){

E toReturn = cursor.element();
cursor = (cursor == list.last())? null: list.next(cursor);
return toReturn;
}

public void remove(){

throw new UnsupportedOperationException();
}



}

编辑:我将 for-each 循环转换为 while 循环,如下所示....

protected void preOrderPositions(Position<E> v,
PositionalList<Position<E>> pos) throws InvalidPositionException {

pos.addLast(v);

Iterator<Position<E>> iter = children(v).iterator();

while (iter.hasNext()) {
Position<E> w = iter.next();
preOrderPositions(w, pos);

}

}

最佳答案

您只能迭代实现了 java.lang.Iterable 的类。但是,您尝试迭代您的自定义可迭代接口(interface)。那行不通:

public interface Iterable <E> { 

public Iterator<E> iterator();

public Iterable<Position<E>> positions(); // <- your custom Iterable class is returned here, NOT java.lang.Iterable

}

如果您想使用可迭代类进行迭代,请扩展 java.lang.Iterable

 public interface Iterable <E> extends java.lang.Iterable<E>


HINT: Do not write classes / interfaces that have the same name as anything in the java.lang package.

关于java - 迭代 java.lang.Iterable 的数组或实例 - 缺少常识解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24369092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com