Im trying to defined a generic LinkedList of type int but it throws me a compile errror
List<int> I = new LinkedList<int>();
Im trying to defined a generic LinkedList of type int but it throws me a compile errror
List<int> I = new LinkedList<int>();
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.
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 int
s 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.
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