0

Im trying to defined a generic LinkedList of type int but it throws me a compile errror

List<int> I = new LinkedList<int>();
user1050619
  • 19,822
  • 85
  • 237
  • 413

3 Answers3

3

You have to use wrapper classes to do that.

  List<Integer> I = new LinkedList<Integer>();

You can insert an int in this linked list as autoboxing will automatically create a Integer object out of this int and add it to the LinkedList.

Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40
1

You can't use a primitive type as a generic type. If you really want to do that, that's what the wrapper classes (Integer, Float, etc.) are for. You can do it like this:

List<Integer> I = new LinkedList<Integer>();

You will still be able to put ints in the list because of autoboxing. If you try to use an int in a situation that requires an Integer, a new Integer will automatically be created with Integer.valueOf and used instead.

Also, in Java 7, you can use the diamond operator and just use this:

List<Integer> I = new LinkedList<>();

There is no advantage to this, except it is faster to type.

tbodt
  • 16,609
  • 6
  • 58
  • 83
1

This is one reason Java has primitive wrapper classes, since you can't use primitives as type arguments. In your case, you need Integer:

List<Integer> I = new LinkedList<Integer>();

In Java 7+ you don't need to reiterate the type parameter:

List<Integer> I = new LinkedList<>();

See also: Generics

arshajii
  • 127,459
  • 24
  • 238
  • 287