简体   繁体   English

如何从 Java Iterator 随机访问数据

[英]How to randomly access data from a Java Iterator

I get an Iterator back from a class and I would like to get the xth element of that iterator.我从一个类中得到一个迭代器,我想得到那个迭代器的第 x 个元素。 I know I could load it into an ArrayList in a loop or check a counter, but that seems inefficient/ugly.我知道我可以在循环中将它加载到 ArrayList 中或检查计数器,但这似乎效率低下/丑陋。 What is the best way to do this?做这个的最好方式是什么?

I thought something like,我想过类似的事情,

List al = new ArrayList(myIterator);
  myval = al.get(6);

But that constructor is undefined.但是那个构造函数是未定义的。 thanks.谢谢。

The definition of an Iterator does not allow arbitrary indexing to a position. Iterator的定义不允许任意索引到位置。 That's just the way it's defined. 这就是它的定义方式。 If you need that capability you will have to load the data into an indexable collection. 如果需要此功能,则必须将数据加载到可索引的集合中。

The point of the Iterator interface is to allow sequential access to a collection without knowing anything about its size. Iterator接口的重点是允许对集合的顺序访问,而无需了解其大小。 Iterators can be forward-only or bi-directional ( ListIterator ). 迭代器可以是仅转发的,也可以是双向的( ListIterator )。 It's just one specific model for accessing elements of a collection. 它只是用于访问集合元素的一种特定模型。 One advantage is that it implies nothing about the collection size, which could be much too large to fit completely into memory. 优点之一是,它并不意味着集合的大小,因为集合的大小可能太大而无法完全容纳到内存中。 By allowing only sequential access, the implementation is free to keep only part of the collection in memory at any given moment. 通过只允许顺序访问,该实现可以在任何给定时刻自由地将集合的仅一部分保留在内存中。

If you need to load the iterator contents into a list you need to do it yourself with a loop. 如果需要将迭代器的内容加载到列表中,则需要自己循环执行。

Nope, you've named the only approaches. 不,您已经指定了唯一的方法。 You're going to end up needing a for loop to iterate to the appropriate position. 您最终将需要一个for循环来迭代到适当的位置。

A few utility libraries have shortcuts to load an Iterator 's contents into an ArrayList , or to get the n th element of an Iterator , but there's nothing built into the JDK. 有几个工具库,具有快捷方式的装载Iterator的内容转换成一个ArrayList ,或者拿到n个的元素Iterator ,但没有什么内置的JDK。

As a workaround i use this in my utils class作为一种解决方法,我在我的 utils 类中使用它

     /**
     * Retrive the position object of iterator 
     * @param iterator
     * @param position
     * @return Object at position
     * @throws Exception 
     */
    public static Object iterateTo(Iterator iterator, int position) throws Exception{
        
        if(iterator == null){
            throw new Exception("iterator == null");
        }

        if(position < 0){
            throw new Exception("position < 0");
        }
        
        while(iterator.hasNext() && position > 0){
            position--;
            iterator.next();
        }
        
        if(position != 0){
            throw new Exception("position out of limit");
        }
        
        return iterator.next();
        
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM