Reputation: 69
Assume we have following example code.
First Class:
public class Template<T> {
private final T val;
public Template(T val) {
this.val = val;
}
public T getVal() {
return val;
}
}
Second class:
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) {
List<?> templates = new ArrayList<Template<?>>();
// How can I cast this without warning?
List<Template<?>> castedTemplates = (List<Template<?>>)templates;
// further code...
}
}
So, my question is: How can I do the cast without warning and without @SuppressWarnings("unchecked")?
Upvotes: 1
Views: 2054
Reputation: 39477
You cannot do it.
This is the point - the compiler has to generate those warnings so that they warn you that you're doing something not quite by the book.
And the @SuppressWarnings("unchecked")
is supposed to suppress them (if that's what you explicitly want).
I know it sounds too trivial as an answer but it's true.
Upvotes: 1
Reputation: 97282
Why would you if you can just define it as List<Template<?>> templates = new ArrayList<Template<?>>();
?
Upvotes: 2