Why fill() and copy() of Collections in java is implemented this way
        Posted  
        
            by 
                Priyank Doshi
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Priyank Doshi
        
        
        
        Published on 2012-09-05T03:36:56Z
        Indexed on 
            2012/09/05
            3:37 UTC
        
        
        Read the original article
        Hit count: 189
        
According to javadoc... Collections.fill() is written as below :
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);
            }
        }
    }
Its easy to understand why they didn't use listIterator for
if (size < FILL_THRESHOLD || list instanceof RandomAccess) 
condition as of RandomAccess. But whats the use of size < FILL_THRESHOLD in above?
I mean is there any significant performance benefit over using iterator for size>=FILL_THRESHOLD and not for size < FILL_THRESHOLD ?
I see the same approach for Collections.copy() also :
 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;
© Stack Overflow or respective owner