According to javadoc ... Collections.fill () is written as follows:
public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } }
Itβs easy to see why they did not use listIterator for
if (size < FILL_THRESHOLD || list instanceof RandomAccess)
with the condition RandomAccess. But what is the use of size < FILL_THRESHOLD in the above?
I mean, is there a significant performance advantage when using iterator for size>=FILL_THRESHOLD and not for size < FILL_THRESHOLD ?
I also see the same approach for Collections.copy ():
public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } }
FYI:
private static final int FILL_THRESHOLD = 25; private static final int COPY_THRESHOLD = 10;
Same approach below:
public static void reverse(List<?> list) public static void shuffle(List<?> list, Random rnd)
EDIT:
My confusion is for the size<FILL_THRESHOLD , not for RandomAccess
Priyank Doshi
source share