为什么我不能初始化一个Map< int,String>?

为什么我不能初始化一个Map< int,String>?

问题描述:

我想存储一组 int / String 值,但 int 不一定是增量的,这意味着数据可以是:

I want to store a set of int/String values, but the ints are not necessarily incremental, meaning the data can be:

<1, "first">, <3, "second">, <9, "third">. 

所以我试图创建一个c#等价的一个 Dictionary< int ,字符串> ,但它只是无法编译,表示语法错误在令牌上int,这个标记之后的尺寸在行上:

So I'm trying to create the c# equivalent of a Dictionary<int, string> but it just fails to compile, saying "Syntax error on token "int", Dimensions expected after this token" on the line:

private Map<int, String> courses;

有人可以告诉我为什么会这样吗?还有一个很好的替代方法是将对象创建为 int String 的占位符,然后使用数组来存储它们

Can anyone please tell me why this is? And a good alternative to creating an object as a placeholder for the int and String, then using an array to store them?

您不能将基本类型用作通用类型参数。

You cannot use primitive types as generic type arguments.

使用

private Map<Integer, String> courses;

查看有关泛型的更多限制这里

See more restrictions on Generics here.

Dev的贡献: JLS指定了只有引用类型(和通配符) )可以用作通用类型参数。

Dev's contribution: the JLS specifies that only reference types (and wildcards) can be used as generic type arguments.