简体   繁体   English

泛型语法:类与原始数据类型

[英]Generics syntax: classes versus primitive data types

Why does this one does not work: 为什么这个不起作用:

ArrayList<LinkedList<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 > ). 因为Java只能将类(而不是基本类型)和数组(也可以是基本类型的数组)用于泛型(在<>之间)。

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. int是一种原始类型,其中Integer只是该类型的包装器类,因此Integer是可以工作的类型。

becuase the definition is LinkedList< T > and only Object can be here < T > . 因为定义是LinkedList< T >并且只有Object可以在此处< T >

int is primitive type so LinkedList< int > - compile error int是原始类型,因此LinkedList< int > - compile error
Integer is object LinkedList < Integer > - right one Integer是对象LinkedList < Integer > - right one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM