Something like the following will not give me a compile-time or runtime error and I’m drawing a blank as to why. Is there a way to enforce a compile error on the call to cls.add?
Why isn’t the definition of T in the class definition being carried over to the call to the methods inside? I understand I didn’t instantiate the class that way, but the definition of the class states T must be a Number.
public class NewClass<T extends Number> {
private List<T> id = new ArrayList<T>();
public void add(List<T> elem) {
id.addAll(elem);
}
public static void main(String[] args) {
NewClass cls = new NewClass();
cls.add(new ArrayList<String>());
}
}
You are using a raw type. All type information is ignored in that case, and you get a warning.
If you provide a type parameter, it will fail: