使用int作为java.util.Dictionary的类型参数 [英] Using int as a type parameter for java.util.Dictionary

查看:234
本文介绍了使用int作为java.util.Dictionary的类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试声明一个字典时:

When I try to declare a Dictionary as such:

private Dictionary<String, int> map;

编译器给我以下错误:

令牌int上的语法错误,此令牌后面的尺寸

Syntax error on token "int", Dimensions expected after this token

但它可以正常工作整数。我模糊地意识到Java对待 int / Integer 不同(我来自.NET背景),但是希望有人可以给我一个完整的解释,为什么我不能在字典中使用原语?

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<>

推荐答案

在Java基元不是对象,所以不能使用它们代替对象。但是Java会自动将box / unbox原语(也称为 autoboxing )转换为对象,以便您可以执行以下操作:

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:

List<Integer> intList = new LinkedList<Integer>();
intList.add(1);
intList.add(new Integer(2));
...
Integer first = intList.get(0);
int second = intList.get(1);

但这只是编译器为您自动转换类型。

But this is really just the compiler automatically converting types for you.

这篇关于使用int作为java.util.Dictionary的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆