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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:38:43  来源:igfitidea点击:

Type mismatch: cannot convert from element type Object to int

java

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

htis 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 htas a LinkedHashMap<Integer, Foo>where Foois whatever data type you expect to be returned by ht.get(). Using the Mapinterface would be even better:

将您希望返回的任何数据类型声明htLinkedHashMap<Integer, Foo>where 。使用界面会更好:Fooht.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 Integers, you should declare it as LinkedHashMap<Integer,Object>.

ht 是 a LinkedHashMap,如果它只包含Integers,则应将其声明为LinkedHashMap<Integer,Object>.

If it will be declared as LinkedHashMap<Integer,Object>, the unboxing to an intwill 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 中的键必须是对象,而不是原始类型。