yoavstr
yoavstr

Reputation: 387

Generics syntax: classes versus primitive data types

Why does this one does not work:

ArrayList<LinkedList<int>> 

where this one does:

ArrayList<LinkedList<Integer>> 

???

Upvotes: 3

Views: 1387

Answers (3)

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

Because Java can only use classes (and not primitive types) and arrays (also arrays for primitives) for generics (between < and >).

List<Integer> list;

That is also a reason why there are wrapper classes for primitive types:

int -> Integer
boolean -> Boolean
double -> Double
byte -> Byte
etc...

Upvotes: 7

user467871
user467871

Reputation:

becuase the definition is LinkedList< T > and only Object can be here < T > .

int is primitive type so LinkedList< int > - compile error
Integer is object LinkedList < Integer > - right one

Upvotes: 0

Chris Cooper
Chris Cooper

Reputation: 17594

The argument in the <> must be an object because those classes can only hold objects.

int is a primitive type, where as Integer is simply a wrapper class for that type, so Integer is the one that will work.

Upvotes: 1

Related Questions