java java中emptyIterator的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26288670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of emptyIterator in java
提问by user3366706
Can anyone let me know what is the real time use of an Empty Iterator in java? I'm curious to know why is it needed? things like,
任何人都可以让我知道 java 中空迭代器的实时用途是什么?我很想知道为什么需要它?像,
1. public static <T> Iterator<T> emptyIterator()
2. public static <T> ListIterator<T> emptyListIterator()
3. public static final <T> Set<T> emptySet(), etc..
source: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyIterator()
来源:http: //docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyIterator()
回答by Damian Leszczyński - Vash
You can use an empty iterator in cases where an API that you implement requires an iterator, but some of your code's logic can yield no items in the result. In that case, instead of returning a null
, you return an empty iterator. You can also use an empty iterator to save some memory and for testing purposes.
在您实现的 API 需要迭代器的情况下,您可以使用空迭代器,但您的某些代码逻辑在结果中不会产生任何项目。在这种情况下,不是返回 a null
,而是返回一个空的迭代器。您还可以使用空迭代器来节省一些内存并用于测试目的。
Here is some example code that prevents returning null
and saves some memory at the same time:
下面是一些防止返回null
并同时节省一些内存的示例代码:
class LazyObjectInitialization {
private Collection<String> items;
public final Iterator<String> items() {
if(items == null || items.isEmpty()) {
return Collections.emptyIterator();
}
return items.iterator();
}
public final add(String item) {
if(items == null) {
items = new ArrayList<>();
}
items.add(item);
}
}
In the above class, the field items
is not initialized until an element is added. So to provide expected behavior in method items()
we return an empty iterator. The benefit from this are as follow:
在上面的类中,在items
添加元素之前不会初始化该字段。所以为了在方法中提供预期的行为,items()
我们返回一个空的迭代器。这样做的好处如下:
Smaller memory consumption
- The class allocates memory only when it is really needed.
Smaller memory mutation
- Until we add something to the object, we never create a new instance of the iterator.
We never return
null
.
更小的内存消耗
- 该类仅在真正需要时才分配内存。
较小的记忆突变
- 在我们向对象添加一些东西之前,我们永远不会创建迭代器的新实例。
我们一去不复返
null
。