java 类型不匹配:无法从元素类型 Object 转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7106173/
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
Type mismatch: cannot convert from element type Object to int
提问by max
I'm getting the following error on the line where it says ht.keySet()
:
我在它说的那一行上收到以下错误ht.keySet()
:
Type mismatch: cannot convert from element type Object to int
类型不匹配:无法从元素类型 Object 转换为 int
ht
is a LinkedHashMap
.
ht
是一个LinkedHashMap
。
for (int key : ht.keySet())
{
if(ht.get(key).size() == 0)
{
System.out.println("There is no errors in " + key) ;
}
else
{
System.out.println("ERROR: there are unexpected errors in " + key);
}
}
回答by Matt Ball
You need to use Java generics.
您需要使用Java 泛型。
Declare ht
as a LinkedHashMap<Integer, Foo>
where Foo
is whatever data type you expect to be returned by ht.get()
. Using the Map
interface would be even better:
将您希望返回的任何数据类型声明ht
为LinkedHashMap<Integer, Foo>
where 。使用界面会更好:Foo
ht.get()
Map
LinkedHashMap<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();
// or preferably
Map<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();
回答by alexblum
It must be: for (Integer key : ht.keySet())...
一定是: for (Integer key : ht.keySet())...
LinkedHashMap<K, V>
where K and V are Objects, not primitiv (int, short ...)
LinkedHashMap<K, V>
其中 K 和 V 是对象,而不是 primitiv (int, short ...)
回答by amit
ht is a LinkedHashMap
, if it contains only Integer
s, you should declare it as LinkedHashMap<Integer,Object>
.
ht 是 a LinkedHashMap
,如果它只包含Integer
s,则应将其声明为LinkedHashMap<Integer,Object>
.
If it will be declared as LinkedHashMap<Integer,Object>
, the unboxing to an int
will be done automatically.
如果将其声明为LinkedHashMap<Integer,Object>
,int
则将自动完成对 an 的拆箱。
(*) even better if you declare it as LinkedHashMap<Integer,[actual-object-type]>
(*) 如果你将它声明为更好 LinkedHashMap<Integer,[actual-object-type]>
回答by Ingo
Use Integer instead of int and it will probably work. The keys in the LinkedHashMap must be objects, not primitive types.
使用 Integer 而不是 int ,它可能会起作用。LinkedHashMap 中的键必须是对象,而不是原始类型。