5

List<String> works with or without but List<int> doesn't. I've always wondered about this.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228

3 Answers3

5

You cannot use primitive types (byte, short, int, etc.). You must use the wrapper type which, in this case, is Integer

List<Integer>

This type of casting is called generics, and you can start learning more about them here.

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.

  • Thanks for that. SO it just casts it as a String object type? –  Jan 31 '11 at 01:25
  • @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