Type argument cannot be of primitive type

问题:

创建泛型集合List的时候报错,提示为:Type argument cannot be of primitive type

 

原因:

泛型类型参数不能是原始数据类型,而应该是对象。因为在编译时会把带泛型的转换成Object类型,而基本数据类型不属于Object,所以比如想放int类型,就需要使用它的封装类Integer类型,而不能是int

 

举例:

错误写法:
List<int> list = new ArrayList<>();

 

正确写法:
List<Integer> list = new ArrayList<>();

 

另外补充一下常见的原始类型与对应的封装类如下:

原始类型 封装类
byte Byte
short Short
char Character
int Integer
long Long
float Float
double Double
boolean Boolean

 

posted @ 2021-08-05 22:38  咖啡&牛奶  阅读(301)  评论(0编辑  收藏  举报