开发者

Generics syntax: classes versus primitive data types

Why does this one does not work:

ArrayList<LinkedLis开发者_JAVA百科t<int>> 

where this one does:

ArrayList<LinkedList<Integer>> 

???


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...


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜