2013-04-01 32 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(); 
    } 

} 

希望它有帮助。