List<String>
works with or without but List<int>
doesn't. I've always wondered about this.
Asked
Active
Viewed 148 times
5

Andrzej Doyle
- 102,507
- 33
- 189
- 228
-
1with or without what? It's probably because String is a class and int is a native type. – Raynos Jan 31 '11 at 01:03
-
with or without what? ooops, 3 seconds too late ^^ – Sören Jan 31 '11 at 01:03
-
2http://en.wikipedia.org/wiki/Generics_in_Java – Mauricio Scheffer Jan 31 '11 at 01:03
-
b/c you can't cast java.lang.Object to int – bestsss Jan 31 '11 at 01:06
-
possible duplicate of [Why don't Generics support primitive types?](http://stackoverflow.com/questions/2721546/why-dont-generics-support-primitive-types) – finnw Jan 31 '11 at 13:20
3 Answers
3
List<int>
doesn't work because Java generics doesn't deal with primitive types - only Objects (or subclasses thereof, like Integer
). You aren't required to specify the type parameter when using a generic class, but the compiler will issue a warning and you'll be required to take care of all the type casting (including dealing with potential ClassCastExceptions
) and such yourself.

Stewart Murrie
- 1,319
- 7
- 12
2
Lists (and other collections) can keep only objects, not primitive types. So you can use List<Integer>
but not List<int>
. String
is also an object — that's why it works.
And regarding the difference between List
and List<String>
: the difference exists only during the compilation. In runtime all both lists are identical.
-
-
@CoolBeans: that doesn't make sense. If you are using Generics, you don't need casts. That's the whole point. The compiler will insert the casts and *guarantee* by type checking that there are no ClassCastExceptions. And the only way you *can get* a ClassCastException is by *doing* a cast. – user207421 Jan 31 '11 at 06:09
-
@EJP: You are right. My comment was backwards. I meant to say you should not do List some = new ArrayList<>(); without specifying a type (generic or not). I will delete my comment. Thanks!!! – CoolBeans Jan 31 '11 at 06:14