开发者

Type mismatch: cannot convert from element type Object to int

I'm getting the following error on the line whe开发者_开发知识库re it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a 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);
    }
}


You need to use Java generics.

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:

LinkedHashMap<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();
// or preferably
Map<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();


ht is a LinkedHashMap, if it contains only Integers, you should declare it as LinkedHashMap<Integer,Object>.

If it will be declared as LinkedHashMap<Integer,Object>, the unboxing to an int will be done automatically.

(*) even better if you declare it as LinkedHashMap<Integer,[actual-object-type]>


It must be: for (Integer key : ht.keySet())...

LinkedHashMap<K, V> where K and V are Objects, not primitiv (int, short ...)


Use Integer instead of int and it will probably work. The keys in the LinkedHashMap must be objects, not primitive types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜