Skip to content

Commit b4f84f6

Browse files
Improve Iterators.single (#122875)
Using an anonymous class here doesn't compile as expected. The resulting class comes out as: ``` class Iterators$1 implements java.util.Iterator<T> { 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.
1 parent b4e95dc commit b4f84f6

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

server/src/main/java/org/elasticsearch/common/collect/Iterators.java

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,22 +34,27 @@ public class Iterators {
3434
* Returns a single element iterator over the supplied value.
3535
*/
3636
public static <T> Iterator<T> single(T element) {
37-
return new Iterator<>() {
37+
return new SingleIterator<>(element);
38+
}
3839

39-
private T value = Objects.requireNonNull(element);
40+
private static final class SingleIterator<T> implements Iterator<T> {
41+
private T value;
4042

41-
@Override
42-
public boolean hasNext() {
43-
return value != null;
44-
}
43+
SingleIterator(T element) {
44+
value = Objects.requireNonNull(element);
45+
}
4546

46-
@Override
47-
public T next() {
48-
final T res = value;
49-
value = null;
50-
return res;
51-
}
52-
};
47+
@Override
48+
public boolean hasNext() {
49+
return value != null;
50+
}
51+
52+
@Override
53+
public T next() {
54+
final T res = value;
55+
value = null;
56+
return res;
57+
}
5358
}
5459

5560
@SafeVarargs
@@ -496,5 +501,4 @@ public static <T> int hashCode(Iterator<? extends T> iterator, ToIntFunction<T>
496501
}
497502
return result;
498503
}
499-
500504
}

0 commit comments

Comments
 (0)