Home > Blockchain >  Why Variable-Parameterized variant of (cast) operator in Java is flagged as unchecked warning and no
Why Variable-Parameterized variant of (cast) operator in Java is flagged as unchecked warning and no

Time:11-09

Consider the following snippet:

class MyClass<E>{
...
public void checkType(Object o){
 if(o instanceof List<E>){ //this gives compilation error
   List<E> list = (List<E>)o; //this gives unchecked warning
 }
}
...
}
  • Here, the instanceof will give a compilation error as the type of E is not known at run-time.
  • Why does the (List<E>)o give a warning? I think this should be reported as an error by the compiler on the same grounds.

I'm not sure if there can be any case why this will not be an error and only qualify as warning.

CodePudding user response:

Just came across this piece of code that suggests why Non-Reified Casts with Type Parameters can be a warning only and not an error:

public static <T> List<T> getAsList(Collection<T> c){
        if(c instanceof List<?>){
            return (List<T>)c;
        }
        ...
    }
  • Related