迭代数据结构的元素而不是Collection

时间:2013-07-09 15:48:32

标签: java generics iterator

我的问题是:我有一个迭代器类,它应该迭代给定数据结构中的元素,<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;
    }
}

1 个答案:

答案 0 :(得分:1)

您将无法使用完全通用的参数<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的实例,但实际上并没有什么不同......

相关问题