我的问题是:我有一个迭代器类,它应该迭代给定数据结构中的元素,<E>
比方说,但我设法完成的是,当我传入数据结构时,它将迭代数据结构本身。
即。 DynamicIterator it = new DynamicIterator(da);
假设 da 是一个数组,输出将是 [1,2,3,4,5,6] 而不是 1,2,3,4,5,6
我的问题最重要的是,比问题本身更了解处理此问题的普遍接受的做法。
编辑代码:
public class X<E>
{
private final E[] rray;
private int currentIndex = 0;
public X(E... a)
{
//if the incoming array is null, don't start
if(a == null)
{
System.out.println("Array is null");
System.exit(1);
}
//set the temp array (rray) to the incoming array (a)
this.rray = a;
}
//hasNext element?
public boolean hasNext()
{
return rray.length > currentIndex;
}
//next element (depends on hasNext())
public E next()
{
if (!hasNext())
{
System.out.println("Element doesn't exist, done");
System.exit(1);
}
return rray[currentIndex++];
}
//return array
public E[] access()
{
return rray;
}
}
最佳答案
您将无法使用完全通用的参数来执行此操作 <E>
- 你会如何遍历 Throwable
, 例如?你类什么X
目前所做的是在其构造函数中接受任意数量的对象,然后简单地依次返回每个对象。
如果您限制传入对象的范围以实现例如Iterable
,然后您实际上可以开始“查看”它们并返回它们的内容:
public class X<E> {
private final Iterator<E> it;
public X(Iterable<E> a) {
it = a.iterator();
}
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
}
尽管这与仅使用 a.iterator()
并没有真正完成任何不同的事情直接代替 X
的实例...
关于java - 遍历数据结构的元素而不是集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552648/