簡體   English   中英

如何獲得數組的迭代器?

[英]How can I get to the iterator of an array?

我想像這樣使用下面的類:

for(String device : new Devices())
{
   //
}

如果我提供對內部字符串數組的直接訪問,則沒有問題:

for(String device : new Devices().getAllDevices()) //getAllDevices would be a String[]
{
   //
}

但是我只想轉發迭代器,如果AllDevicesArrayList ,這將很簡單。

public final class Devices implements Iterable<String>{

    private static final String MyKindleFire = "123156448975312";

    private static final String[] AllDevices = new String[]{MyKindleFire};

    @Override
    public Iterator<String> iterator() {
        // if AllDevices were an array list, this would be possible
        // but how should I do this for an array?
        return AllDevices.iterator();
    }   
}

這可行,但是我想知道一種更好的方法:

@Override
public Iterator<String> iterator() {
    return Arrays.asList(AllDevices).iterator();
}

不幸的是,如果不將數組轉換為List<T> ,就無法做到這一點:使用for循環的“ foreach”版本在數組上進行迭代是“編譯器的把戲”,即編譯器在內部知道並做的事情。

在“ foreach”循環中使用原語的能力是間接指示Iterator<T>不在此處使用,因為Java泛型不能與原語類型一起使用。

String[] someArray = ....;
List<String> someList = java.util.Arrays.asList(someArray);
someList.iterator();

我認為這是在純Java中獲取數組迭代器的唯一方法。

如果您正在使用apache commons-collection,則可以簡單地使用:

org.apache.commons.collections.IteratorUtils.arrayIterator(Object[])

參見http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections/IteratorUtils.html

您可以使用Guava的Iterators.forArray(T...)進行迭代。

或者,從數組中創建一個Iterable (例如,使用Arrays.asList(T...) )並返回其.iterator()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM