Why do generics in Java work with classes but not with primitive types?
For example, this works fine:
List foo = new ArrayList
In java generics are implemented by using "Type erasure" for backward compatibility. All generic types are converted to Object at runtime. for example,
public class Container {
private T data;
public T getData() {
return data;
}
}
will be seen at runtime as,
public class Container {
private Object data;
public Object getData() {
return data;
}
}
compiler is responsible to provide proper cast to ensure type safety.
Container val = new Container();
Integer data = val.getData()
will become
Container val = new Container();
Integer data = (Integer) val.getData()
Now the question is why "Object" is chose as type at runtime?
Answer is Object is superclass of all objects and can represent any user defined object.
Since all primitives doesn't inherit from "Object" so we can't use it as a generic type.
FYI : Project Valhalla is trying to address above issue.