[PATCH] Duplicated indexOf/lasIndexOf in array-based collections

Martin Buchholz martinrb at google.com
Mon Mar 26 18:46:56 UTC 2018

Сергей, I'm sort of maintaining all those collection classes, and I have on
occasion also wanted to have indexOf methods in Array.java.  But:

Arrays are generally discouraged.  Any new static methods on Arrays (or,
where I actually want them, on the array object itself!  Requires a java
language change!) will meet resistance.

We've come to regret supporting nulls in collections, so newer collection
classes like ArrayDeque don't support them.

Another variant users might want is what kind of equality comparison to use.

We've come to regret having ArrayList with zero-based start index - it
would have been better to have ArrayDeque's circular array behavior in from
day one.

The code to search array slices is very small, so you're not saving much.
It's easy to make an off-by-one error, but that's true for an Arrays API as

On Sat, Mar 10, 2018 at 12:42 AM, Сергей Цыпанов <sergei.tsypanov at yandex.ru>

> Hi everyone,
> currently array-based collections, in particular java.util.ArrayList,
> java.util.Arrays$ArrayList, java.util.Vector, java.util.concurrent.CopyOnWriteArrayList
> have duplicated code in indexOf() and lastIndexOf().
> My proposal is to extract this code into java.util.Arrays helping JIT and
> saving space in ReservedCodeCache.
> Moreover, developers quite often use code snippets like
> Arras.asList(array).indexOf(obj)
> Arras.asList(array).contains(obj)  or even
> Arrays.stream(names).anyMatch(existing -> existing.equals(name));
> or write similar utility code for allocation-free cases like the one in
> https://github.com/hibernate/hibernate-orm/blob/
> 0a2a5c622e3eb30724e80bc8661c0ac55ebfb2be/hibernate-core/src/
> main/java/org/hibernate/bytecode/enhance/internal/
> tracker/SimpleFieldTracker.java#L40
> Also see
> https://github.com/JetBrains/intellij-community/blob/
> 200f59d7cf3b0f66feb3a4abebbb90864dc5edc7/platform/util/src/
> com/intellij/util/ArrayUtil.java#L726
> https://github.com/JetBrains/intellij-community/blob/
> 200f59d7cf3b0f66feb3a4abebbb90864dc5edc7/platform/util-rt/
> src/com/intellij/util/ArrayUtilRt.java#L63
> https://github.com/spring-projects/spring-framework/blob/
> 5f4d1a4628513ab34098fa3f92ba03aa20fc4204/spring-oxm/src/
> main/java/org/springframework/oxm/jibx/JibxMarshaller.java#L256
> If java.util.Arrays incorporates contains() and indexOf() then all that
> boilerplate can be replaced with usage of JDK-provided standard API.
> Patch is attached to this mail.
> Regards,
> Sergey Tsypanov

More information about the core-libs-dev mailing list