Why is the Stream.sorted not type safe in Java 8?

  • A+

This is from the Stream interface from Oracles implementation of JDK 8:

public interface Stream<T> extends BaseStream<T, Stream<T>> {     Stream<T> sorted(); }  

and it is very easy to blow this in run-time and no warning will be generated in compile time, here is an example:

class Foo {     public static void main(String[] args) {         Arrays.asList(new Foo(), new Foo()).stream().sorted().forEach(f -> {});     } } 

which will compile just fine but will throw an exception in runtime:

Exception in thread "main" java.lang.ClassCastException: Foo cannot be cast to java.lang.Comparable 

What can be the reason that sorted method was not defined where compiler could actually catch such problems? Maybe I am wrong but isn 't it this simple:

interface Stream<T> {     <C extends Comparable<T>> void sorted(C c); } 


Obviously the guys implementing this (who are light years ahead of me as far as programming and engineering is considered) must have a very good reason that I am unable to see, but what is that reason?


How would you implement that? sorted is a intermediate operation (can be called anywhere between other intermediate operations), meaning you can start with a stream that is not Comparable, but call sorted on one that is Comparable:

Arrays.asList(new Foo(), new Foo())       .stream()       .map(Foo::getName) // name is a String for example       .sorted()       .forEach(f -> {}); 

The thing that you are proposing takes an argument as input, but Stream::sorted does not, so you can't do that. The overload version accepts a Comparator - meaning you can sort something by a property, but still return Stream<T>. I think that this is quite easy to understand if you would try to write your minimal skeleton of a Stream interface/implementation.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: