对象的迭代器[] [英] Iterator of Object[]
问题描述
有没有办法获取数组的迭代器?类似的东西:
Is there a way to obtain the iterator of an array? Something like that:
class MyCollection implements Iterable<String> {
String[] items;
@Override
public Iterator<String> iterator() {
return items.iterator(); //obviously, it doesn't compile.
}
}
推荐答案
您可以使用 Arrays.asList
:
You could use Arrays.asList
:
return Arrays.asList(items).iterator();
它只是将数组包装在一个列表实现中,以便可以调用 iterator()
方法。
It simply wraps the array in a list implementation so that you can just call the iterator()
method on it.
请注意,此方法只适用于对象数组。对于原始数组,你必须实现自己的迭代器(例如使用匿名类)。
Be aware that this approach will only works with array of objects. For primitive arrays you would have to implement your own iterator (with an anonymous class for instance).
从Java 8开始,还可以使用
Arrays.stream
获取一个迭代器,并且如果项
是 int []
, double []
或 long []
):
return Arrays.stream(items).iterator();
虽然你不能使用原始数据类型 char
,
float
和 short
,因为没有相应的流实现。但您可以使用此解决方法:
though you won't be able for the primitive data types char
, float
and short
as there are no corresponding stream implementations. You could however use this workaround:
return IntStream.range(0, items.length).mapToObj(i -> items[i]).iterator();
这篇关于对象的迭代器[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!