2013-04-01 34 views
1

Python有itertools庫,它允許無限循環一列項目。Python中的itertools循環函數

cycle('ABCD') --> A B C D A B C D ... 

如何在java中實現相同的數組?例如:

int[] a = { 1, 2, 3, 4}; 
cycle(a) = 1, 2, 3, 4, 1, 2, 3, 4 .... 

回答

2

如何:

public void cycle(int[] a) { 
    while (true) { 
     for (int val : a) { 
      ... 
     } 
    } 
} 

,使其與回調有用:

public interface Callback<T> { 
    public void execute(T value); 
} 

public <T> void cycle(T[] a, Callback<T> callback) { 
    while (true) { 
     for (T val : a) { 
      callback.execute(val); 
     } 
    } 
} 
5

如果使用番石榴是它已經有一個選項,以:

Iterables.cycle 
+0

這對原始數組無效(本身),但你可以例如使用'Ints.asList'將一個'int []'變成'List '。 –

+0

@LouisWasserman是的,我意識到這一點。我只是寫了一個快速的答案.. thx雖然! – Eugene

+0

@LouisWasserman o darn!你是番石榴的創造者! :)是的,老師! – Eugene

0

有趣的,你也可以做一個迭代器像這樣。

public static void main(String[] args) { 
Integer[] A = new Integer[]{1,2,3}; 
CyclicArrayIterator<Integer> iter = new CyclicArrayIterator<>(A); 
    for(int i = 0; i < 10; i++){ 
    System.out.println(iter.next()); 
    } 
} 

番石榴的方法似乎最乾淨,但如果你不想包括任何依賴關係。這是您可以使用的CyclicIterator類。

/** 
* An iterator to loop over an array infinitely. 
*/ 
public class CyclicArrayIterator<T> implements Iterator<T> { 

    private final T[] A; 
    private int next_index = 0; 

    public CyclicArrayIterator(T[] array){ 
    this.A = array; 
    } 

    @Override 
    public boolean hasNext() { 
    return A[next_index] != null; 
    } 

    @Override 
    public T next() { 
    T t = A[next_index % A.length]; 
    next_index = (next_index + 1) % A.length; 
    return t; 
    } 

    @Override 
    public void remove() { 
    throw new ConcurrentModificationException(); 
    } 

} 

希望它有幫助。