说我有一个自定义类。
public class CustomClass {
private String name;
private String data;
public CustomClass(String name, String data) {
this.name = name;
this.data = data;
}
}
我也有一个自定义类对象的列表。
CustomClass[] list = new CustomClass[] {
new CustomClass("Item 1", "data"),
new CustomClass("Item 2", "data"),
new CustomClass("Item 3", "data"),
new CustomClass("Item 4", "data"),
new CustomClass("Item 5", "data"),
};
我更喜欢 "内联 "的解决方案(不需要创建任何新的类)。
比如说,我需要一个接一个地获取我的CustomClass列表项K=7次。该解决方案应该检索到以下CustomClass对象。
Item 1 Item 2 Item 3 Item 4 Item 5 Item 1 Item 2
试试使用索引模数组长度
for(int i=0;i<K;i++){
list[i%list.length]; //do sth with that, I just wrote what you get
}
所以,当它到了第一个索引(这里命名为i)大于或等于列表长度时,它将 "重置 "它,因为操作modulo (%)返回整数除法后的剩余部分。
编辑:解决方案确实是符合的,不需要实例化任何类。
希望能帮到你:)
试试这个。
static <T> Iterator<T> circularIterator(List<T> list, int count) {
int size = list.size();
return new Iterator<T>() {
int i = 0;
@Override
public boolean hasNext() {
return i < count;
}
@Override
public T next() {
return list.get(i++ % size);
}
};
}
试试这个。
List<String> list = Arrays.asList("a", "b", "c");
for (Iterator<String> i = circularIterator(list, 5); i.hasNext();) {
String s = i.next();
System.out.println(s);
}
的结果。
a
b
c
a
b
一个简单的方法是:
import com.google.common.collect.Iterables
import com.google.common.collect.Iterators;
Integer[] arr = {1,2,3,4,5};
Iterator<Integer> iter = Iterators.limit(Iterables.cycle(arr).iterator(),7) ;
这里有一个Java 8友好的方法。
IntStream.range(0, K)
.mapToObj(i -> list[i % list.length])
.forEach(cc -> /* play with CustomClass cc instance */);