Why do generics in Java work with classes but not with primitive types?
For example, this works fine:
List<Integer> foo = new ArrayList<Integer>();
but this is not allowed:
List<int> bar = new ArrayList<int>();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Generics in Java are an entirely compile-time construct – the compiler turns all generic uses into casts to the right type. This is to maintain backwards compatibility with previous JVM runtimes.
This:
gets turned into (roughly):
So, anything that is used as generics has to be convertable to Object (in this example
get(0)returns anObject), and the primitive types aren’t. So they can’t be used in generics.