0

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;
    }
}
scgotts
  • 11
  • 1
  • Do you know the contents of `Optional`? – brso05 Jan 19 '17 at 20:30
  • 1
    Are you sure that `new Optional<>(10)` compiles for you? And since I hope you wanna do research: check out it is important that `Optional` is `final` and your class isn't. – Tom Jan 19 '17 at 20:42
  • Possible duplicate of [ClassCastException vs. "cannot cast" compilation error](http://stackoverflow.com/questions/19895304/classcastexception-vs-cannot-cast-compilation-error) – Tom Jan 19 '17 at 20:45
  • The dupe uses different classes, but the answers explains what's happening here. – Tom Jan 19 '17 at 20:45
  • No subclass of Optional can be a Collection as Optional is `final`. Try making your class `final` – Peter Lawrey Jan 19 '17 at 21:19

1 Answers1

0

Tom pointed me to the duplicate which answered the question, see ClassCastException vs. "cannot cast" compilation error

TO re-hash, I changed MyClass to final and it gave a compile time error. Optional is also a final class.

Thanks

Community
  • 1
  • 1
scgotts
  • 11
  • 1
  • Don't answer this question if you also see that this is a duplicate. Accept the duplicate instead (there should be a notification above the question). – Tom Jan 19 '17 at 22:24