overloads for java.util.RandomAccess

Gernot Neppert mcnepp02 at googlemail.com
Wed Oct 31 00:47:40 PDT 2012


Hello all,

while trying to get an overview of the various factory methods in
java.util.streams.Streams, it grabbed my attention that the 'tagging
interface' java.util.RandomAccess has been chosen there as an overload
discriminator. I think that's a premiere in the entire JDK!

Take a look at this one, for example:

    public static <T, L extends RandomAccess & List<T>> Stream<T> stream(L
source) ;

This overload will obviously only be picked by the compiler if a 'source'
is passed whose static type implements java.util.RandomAccess, such as
java.util.ArrayList. Should you invoke it in a context where the static
type is 'java.util.List<T>', it will not be picked, and the overload

    public static<T> Stream<T> stream(Collection<T> source);

will be picked instead. This is very likely to happen, which would be a
shame!

So, I suggest to replace it with the following overload which takes the
established approach of testing for 'RandomAccess' explicitly:

 public static <T> Stream<T> stream(List<T> source) {
if(source instanceof RandomAccess) {
        return new ValuePipeline<>(new
RandomAccessListStreamAccessor<T,L>(source));
    }


More information about the lambda-dev mailing list