Java 8 Interfaces with static methods : understanding it using Collections framework

KItis Source

As I have read in many places, Java 8 static methods in interfaces are meant for avoiding the case where we have to write a separate package-private class for utility methods. However, when I examine the Java 8 collections class, I see it still has some utility methods that could be moved to the collections interface.

For instance, the reverse method is still in the collections class. and there are other examples as well. I would like to know, why some methods are moved to the collections interface while others are still kept inside the collections utility class.

@SuppressWarnings({"rawtypes", "unchecked"})
public static void reverse(List<?> list) {
    int size = list.size();
    if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
            swap(list, i, j);
    } else {
        // instead of using a raw type here, it's possible to capture
        // the wildcard but it will require a call to a supplementary
        // private method
        ListIterator fwd = list.listIterator();
        ListIterator rev = list.listIterator(size);
        for (int i=0, mid=list.size()>>1; i<mid; i++) {
            Object tmp = fwd.next();
            fwd.set(rev.previous());
            rev.set(tmp);
        }
    }
}

Update,

Sort method is moved to List interface by putting it as a default method like below

@SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

then, in order to support backward compatibility, they have still kept the sort method in Collections class as well.

public static <T extends Comparable<? super T>> void sort(List<T> list) {
        list.sort(null);
    }

why can't we do the same thing for reverse as well.

javadesign-patternscollectionsjava-8

Answers

comments powered by Disqus