Java:HashMap<String,int>不起作用

147

HashMap<String, int> 似乎不能工作,但是 HashMap<String, Integer> 能工作。 有什么想法吗?


你的问题用词有些混淆,能否澄清一下?具体哪里出了问题,可以贴上代码吗? - Anthony Forloney
5个回答

228

在Java中,您不能使用基本类型作为泛型参数。请改用:

Map<String, Integer> myMap = new HashMap<String, Integer>();

使用自动装箱/拆箱代码的区别很小。 自动装箱意味着您可以编写:

myMap.put("foo", 3);

替换为:

myMap.put("foo", new Integer(3));

自动装箱意味着第一个版本被隐式转换为第二个版本。自动拆箱意味着您可以编写:

int i = myMap.get("foo");

改为:

int i = myMap.get("foo").intValue();

隐式调用intValue() 意味着如果找不到键,它将生成一个NullPointerException,例如:

int i = myMap.get("bar"); // NullPointerException
原因是类型擦除。与 C# 不同,泛型类型不会在运行时保留。它们只是一种“语法糖”,用于显式转换以避免进行以下操作:
Integer i = (Integer)myMap.get("foo");

举个例子,这段代码是完全合法的:

Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");

3
你的最后一个例子有问题:无法将Map<String,Integer>转换为Map<Integer,String>。 - T3rm1
将每个单独的代码放在新行中,因为使用get()方法时,第5行的代码被视为对象,所以在使用intValue()方法之前必须先将其转换为整数。 - fresh learner

5

2

HashMap 中不能使用基本数据类型。例如,intdouble 是不可行的。您必须使用它们对应的封装类型。

Map<String,Integer> m = new HashMap<String,Integer>();

现在两者都是对象,所以这将起作用。

1

int是一种原始类型,在Java中可以通过这里了解原始类型的含义,而Map是一个接口,需要两个对象作为输入:

public interface Map<K extends Object, V extends Object>

对象是一种类,这意味着您可以创建另一个继承自它的类,但您不能创建一个从int继承的类。因此,您不能将int变量用作对象。我有两个解决方案来解决您的问题:

Map<String, Integer> map = new HashMap<>();

或者

Map<String, int[]> map = new HashMap<>();
int x = 1;

//put x in map
int[] x_ = new int[]{x};
map.put("x", x_);

//get the value of x
int y = map.get("x")[0];

-3

你可以在泛型参数中使用引用类型,而不是原始类型。 因此,在这里你应该使用

Map<String, Integer> myMap = new HashMap<String, Integer>();

并将值存储为

myMap.put("abc", 5);

2
这并没有回答问题。 - smac89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接