问题描述
在Java中,我需要从我的方法返回一个迭代器。我的数据来自另一个对象,通常可以给我一个迭代器,所以我可以返回,但在某些情况下,底层数据为null。为了一致性,我想返回一个空迭代器在这种情况下,所以我的调用者不必测试为null。
In Java, I need to return an Iterator from my method. My data comes from another object which usually can give me an iterator so I can just return that, but in some circumstances the underlying data is null. For consistency, I want to return an "empty" iterator in that case so my callers don't have to test for null.
我想写一些类似: / p>
I wanted to write something like:
public Iterator<Foo> iterator() {
if (underlyingData != null) {
return underlyingData.iterator(); // works
} else {
return Collections.emptyList().iterator(); // compiler error
}
}
但是Java编译器抱怨返回 Iterator< Object>
而不是 Iterator< Foo>
。投放到(Iterator< Foo>)
也不起作用。
But the Java compiler complains about the returning Iterator<Object>
instead of Iterator<Foo>
. Casting to (Iterator<Foo>)
doesn't work either.
推荐答案
p>您可以通过以下语法获得类型为Foo的空列表:
You can get an empty list of type Foo through the following syntax:
return Collections.<Foo>emptyList().iterator();
这篇关于Java迭代器在参数化类型的空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!