I discovered a bug in some old code which obviously will never work. However, it is a runtime exception rather than a compile time exception. I swapped out my custom class for a standard Java class and I get a compile error.
What is the difference that causes one to be a Unchecked cast (runtime exception) while the other is an Inconvertible Types (compile exception)?
GenTest.java
import java.util.Collection;
import java.util.Optional;
public class GenTest {
public static void main(String[] args) {
try {
MyClass<Integer> a = new MyClass<>(10);
// This generates a warning but compiles, then fails at runtime
Collection<MyClass<Integer>> runtimeFail = (Collection<MyClass<Integer>>) a;
} catch (ClassCastException cce) {
cce.printStackTrace();
System.out.println("encountered expected runtime error");
}
Optional<Integer> b = Optional.of(10);
// This generates a compile time exception
//Collection<Optional<Integer>> compileFail = (Collection<Optional<Integer>>) b;
}
}
MyClass.java
public class MyClass<T> {
T value;
public MyClass(T value) {
this.value = value;
}
}