From c2086ec41f2f6b9fa25bf8132224c92745c7bf05 Mon Sep 17 00:00:00 2001 From: Armin Braun Date: Tue, 18 Feb 2025 17:57:47 +0100 Subject: [PATCH] Improve Iterators.single Using an anonymous class here doesn't compile as expected. The resulting class comes out as: ``` class Iterators$1 implements java.util.Iterator { private T value; final java.lang.Object val$element; Iterators$1(java.lang.Object); ``` which seemingly also does not get fixed by the JIT compiler, judging by heap dumps. Lets just use a named class to clean this up and make things a bit more compact and save some heap as well here and there potentially. --- .../common/collect/Iterators.java | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/common/collect/Iterators.java b/server/src/main/java/org/elasticsearch/common/collect/Iterators.java index 73da3f54fd8d7..69b43303df5d9 100644 --- a/server/src/main/java/org/elasticsearch/common/collect/Iterators.java +++ b/server/src/main/java/org/elasticsearch/common/collect/Iterators.java @@ -34,22 +34,27 @@ public class Iterators { * Returns a single element iterator over the supplied value. */ public static Iterator single(T element) { - return new Iterator<>() { + return new SingleIterator<>(element); + } - private T value = Objects.requireNonNull(element); + private static final class SingleIterator implements Iterator { + private T value; - @Override - public boolean hasNext() { - return value != null; - } + SingleIterator(T element) { + value = Objects.requireNonNull(element); + } - @Override - public T next() { - final T res = value; - value = null; - return res; - } - }; + @Override + public boolean hasNext() { + return value != null; + } + + @Override + public T next() { + final T res = value; + value = null; + return res; + } } @SafeVarargs @@ -496,5 +501,4 @@ public static int hashCode(Iterator iterator, ToIntFunction } return result; } - }