使用 int 作为 java.util.Dictionary 的类型参数
当我尝试这样声明字典时:
private Dictionary<String, int> map;
编译器给出以下错误:
标记“int”存在语法错误,此标记后应有维度
但它可以与 Integer
配合使用。我隐约意识到Java以不同的方式对待int
/ Integer
(我来自.NET背景),但我希望有人能给我一个完整的解释为什么我不能在 Dictionary<> 中使用基元
When I try to declare a Dictionary as such:
private Dictionary<String, int> map;
The compiler gives me the following error:
Syntax error on token "int", Dimensions expected after this token
But it works fine with Integer
. I'm vaguely aware that Java treats int
/ Integer
differently (I come from a .NET background), but I was hoping someone could give me a full explanation on why I can't use primitives in a Dictionary<>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Java 中,原语不是对象,因此您不能使用它们来代替对象。然而,Java 会自动装箱/拆箱原语(又名 自动装箱) 转换为对象,这样你就可以执行以下操作:
但这实际上只是编译器自动为你转换类型。
In Java primitives aren't objects, so you can't use them in place of objects. However Java will automatically box/unbox primitives (aka autoboxing) into objects so you can do things like:
But this is really just the compiler automatically converting types for you.
在.Net 中,“原始”类型由对象支持。在 Java 中,基本类型和对象之间存在严格的区别。 Java 5 引入了自动装箱,在某些情况下可以在两者之间进行强制。但是,由于 Java 泛型系统使用类型擦除,因此在这种情况下没有足够的信息来自动装箱。
In .Net, "primitive" types are backed by objects. In Java, there's a hard distinction between primitive types and Objects. Java 5 introduced autoboxing, which can coerce between the two in certain situations. However, because the Java generics system uses type-erasure, there isn't enough information to autobox in this case.
Java 集合只允许引用,不允许基元。您需要使用包装类(在本例中为 java.lang.Integer)来完成您想要的操作:
您可以执行以下操作:
and
Java 使用自动装箱/拆箱来为您处理转换的详细信息。
这里对此有一些说明。
Java collections only allow references not primitives. You need to use the wrapper classes (in this case java.lang.Integer) to do what you are after:
they you can do things like:
and
and Java uses autoboxing/unboxing to deal with the details of the conversion for you.
Here is a little description on it.
扩展 TofuBeer 的答案。
int 是一个原始
整数,是一个对象。
泛型不支持基元。
To expand on TofuBeer's answer.
int is a primitive
Integer is an Object.
Generics does not support primitives.
这就是指定类型使其与基元一起使用的技巧
在您的适配器中
使用相同的包信息将意味着您在该包的全局范围内执行此操作
在实验后发现了这一点。
Thats the trick specify type to make it work with primitives
In your adapter
using the same in package-info will mean you do it globally for that package
Found this after experimenting.
因为在 Java 中,原语是真正的原语。在 Java 中,
int
将按值传递,而Integer
将传递引用。在.NET中,int或Int32等只是不同的名称。Because in Java the primitives are truely primitives. In Java
int
will pass by value, whileInteger
will pass a reference. In .NET int or Int32 etc. are just different names.