This is from the Stream interface from Oracle's implementation of JDK 8:
public interface Stream<T> extends BaseStream<T, Stream<T>> {
Stream<T> sorted();
}
and it is very easy to blow this up at run time and no warning will be generated at 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 at run time:
Exception in thread "main" java.lang.ClassCastException: Foo cannot be cast to java.lang.Comparable
What could be the reason that the sorted
method was not defined where the 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?
Copyright License:
Author:「Koray Tugay」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/53219523/why-is-stream-sorted-not-type-safe-in-java-8