diff --git a/android/guava/src/com/google/common/collect/Iterators.java b/android/guava/src/com/google/common/collect/Iterators.java index 61aece3f27d3..e1284fe27990 100644 --- a/android/guava/src/com/google/common/collect/Iterators.java +++ b/android/guava/src/com/google/common/collect/Iterators.java @@ -1106,24 +1106,36 @@ protected T get(int index) { */ public static UnmodifiableIterator singletonIterator( @ParametricNullness T value) { - return new UnmodifiableIterator() { - boolean done; + return new SingletonIterator<>(value); + } - @Override - public boolean hasNext() { - return !done; - } + private static final class SingletonIterator + extends UnmodifiableIterator { + private static final Object SENTINEL = new Object(); - @Override - @ParametricNullness - public T next() { - if (done) { - throw new NoSuchElementException(); - } - done = true; - return value; + private Object valueOrSentinel; + + SingletonIterator(T value) { + this.valueOrSentinel = value; + } + + @Override + public boolean hasNext() { + return valueOrSentinel != SENTINEL; + } + + @Override + @ParametricNullness + public T next() { + if (valueOrSentinel == SENTINEL) { + throw new NoSuchElementException(); } - }; + // The field held either a T or SENTINEL, and it turned out not to be SENTINEL. + @SuppressWarnings("unchecked") + T t = (T) valueOrSentinel; + valueOrSentinel = SENTINEL; + return t; + } } /** diff --git a/guava/src/com/google/common/collect/Iterators.java b/guava/src/com/google/common/collect/Iterators.java index 61aece3f27d3..e1284fe27990 100644 --- a/guava/src/com/google/common/collect/Iterators.java +++ b/guava/src/com/google/common/collect/Iterators.java @@ -1106,24 +1106,36 @@ protected T get(int index) { */ public static UnmodifiableIterator singletonIterator( @ParametricNullness T value) { - return new UnmodifiableIterator() { - boolean done; + return new SingletonIterator<>(value); + } - @Override - public boolean hasNext() { - return !done; - } + private static final class SingletonIterator + extends UnmodifiableIterator { + private static final Object SENTINEL = new Object(); - @Override - @ParametricNullness - public T next() { - if (done) { - throw new NoSuchElementException(); - } - done = true; - return value; + private Object valueOrSentinel; + + SingletonIterator(T value) { + this.valueOrSentinel = value; + } + + @Override + public boolean hasNext() { + return valueOrSentinel != SENTINEL; + } + + @Override + @ParametricNullness + public T next() { + if (valueOrSentinel == SENTINEL) { + throw new NoSuchElementException(); } - }; + // The field held either a T or SENTINEL, and it turned out not to be SENTINEL. + @SuppressWarnings("unchecked") + T t = (T) valueOrSentinel; + valueOrSentinel = SENTINEL; + return t; + } } /**