Arsen
Arsen

Reputation: 664

Unchecked cast warning only on generic type

Code sample #1:

public class Foo implements Cacheable {
}

public class Fooer {
    void doSomething(Cacheable obj) {
        Foo foo = (Foo) obj; //#1
    }
}

Code sample #2:

public class GenericFooer<FooClass extends Cacheable> {
    void doSomething(Cacheable obj) {
        FooClass foo = (FooClass) obj; //#2
    }
}

Why do I get an "Unchecked cast: 'Cacheable' to 'FooClass'" warning in case of #2 but NOT in case of #1? This two cases seem exactly the same for me. Am I missing something, or is the code inspector slightly broken?

PS: I'm using InteliJ IDEA Community Edition.

PSS: I know how to get around this warning, the only question is why is it here, if it's not there.

Upvotes: 4

Views: 522

Answers (1)

tryingToLearn
tryingToLearn

Reputation: 11663

In both the cases, you are doing something that can not be guaranteed. You are casting the obj to Foo before actually making sure that it will be Foo. So why different behavior?

In case of #1: By using a cast (Foo) you are telling the compiler to trust you that Cacheable obj will definitely be Foo. So compiler just checks the class hierarchy and continues. (In case you try to cast object between different class hierarchies, you will get an error) However in case it does not turn out to be Foo, at run-time ClassCastException will be thrown.

In case of #2: Generics are inherently designed to provide tighter type checks. See Java Doc: Java Generics

So the compiler makes sure to provide you the warning.

Also have a look at Generics: Type Erasure

Upvotes: 2

Related Questions