Java 为什么我不能初始化 Map<int, String>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18729550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't I initialize a Map<int, String>?
提问by Thomas
I want to store a set of int
/String
values, but the int
s are not necessarily incremental, meaning the data can be:
我想存储一组int
/String
值,但int
s 不一定是增量的,这意味着数据可以是:
<1, "first">, <3, "second">, <9, "third">.
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:
因此,我正在尝试创建与 a 等效的 c#,Dictionary<int, string>
但它只是无法编译,并在行中说“令牌“int”上的语法错误,此令牌后预期的尺寸”:
private Map<int, String> courses;
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?
谁能告诉我这是为什么?还是创建一个对象作为int
and的占位符String
,然后使用数组来存储它们的好方法?
采纳答案by Sotirios Delimanolis
You cannot use primitive types as generic type arguments.
您不能将原始类型用作泛型类型参数。
Use
用
private Map<Integer, String> courses;
See more restrictions on Generics here.
在此处查看有关泛型的更多限制。
Dev's contribution: the JLS specifiesthat only reference types (and wildcards) can be used as generic type arguments.
Dev 的贡献:JLS 规定只有引用类型(和通配符)可以用作泛型类型参数。