我的问题是这样的:我有一个迭代器类,它应该遍历给定的数据结构中的元素,我们可以说,但是我设法完成的是当我传入数据结构,它将迭代数据结构本身。迭代通过数据结构的元素而不是集合
即。 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;
}
}
你可以使用反射来做到这一点。按照本教程从类中获取每个字段和值:http://tutorials.jenkov.com/java-reflection/fields.html。 –
感谢您的回应!我会给它一个镜头。 – Hans
这里的问题是我们不知道任何关于底层数据结构的知识,只能说你可以迭代它。 – Hans