如何创建一个不变的迭代器? [英] how to create an immutable iterator?

查看:152
本文介绍了如何创建一个不变的迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个Map或List并从中获取一个迭代器,例如:

If I have a Map or a List and get an iterator from it, for example:

var map = new HashMap();
var iterator = map.entrySet().iterator();

如果事后修改了该映射,它将影响迭代器,还是一旦创建该迭代器基本上是不可变的?

if something modifies that map after the fact, will it affect the iterator or is the iterator basically immutable once created?

如果它不是不可变的,如何创建不可变的迭代器?

推荐答案

迭代器的唯一有效操作是增量和取消引用(尽管Java Iterator在其

The only valid operations for an iterator are increment and dereference (although the Java Iterator combines the two in its next() method). If you have an unmodifiable iterator, that leaves you only dereferencing. The dereferencing can either give you an object reference, or it can be not valid to dereference because it does not refer to a valid position in the collection.

但是这些语义与 :Optional可以为空或具有有效的对象引用.因此,从 Iterator创建一个Optional 并将其用作不可修改的迭代器":

But those are the same semantics as Optional: an Optional can either be empty or have a valid object reference. So, create an Optional from the Iterator and use that as your "unmodifiable iterator":

private Optional<T> unmodifiableNext(Iterator<T> i)
{
   if (i.hasNext()) {
      return Optional.ofNullable(i.next());
   } else {
      return Optional.empty();
   }
}

这还有一个好处,就是Optional不再绑定到集合,因此可以安全地更改集合,而无需更改Optional引用的对象.

This has the additional benefit that the Optional is no longer tied to the collection, so the collection can be safely changed without changing which object the Optional refers to.

这篇关于如何创建一个不变的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆