Optimized version of CopiesList.hashCode()

Zheka Kozlov orionllmain at gmail.com
Mon Nov 26 05:01:46 UTC 2018


Currently, CopiesList.hashCode() is inherited from AbstractList which:

   - calls hashCode() for each element,
   - creates a new Iterator every time.

However, for Collections.nCopies():

   - All elements are the same. So hashCode() can be called only once.
   - An Iterator is unnecessary.

So, I propose overridding hashCode() implementation for CopiesList:

@Override
public int hashCode() {
    int hashCode = 1;
    final int elementHashCode = (element == null) ? 0 : element.hashCode();
    for (int i = 0; i < n; i++) {
        hashCode = 31*hashCode + elementHashCode;
    }
    return hashCode;
}

Benchmark:
List<List<String>> list = Collections.nCopies(10_000, new
ArrayList<>(Collections.nCopies(1_000_000, "a")));
long nano = System.nanoTime();
System.out.println(list.hashCode());
System.out.println((System.nanoTime() - nano) / 1_000_000);

Result:
Old version - ~12 seconds.
New version - ~10 milliseconds.


More information about the core-libs-dev mailing list