2011-08-18 137 views
1

我收到就行了以下错误在那里说:ht.keySet()类型不匹配:不能从元素类型对象转换为int

类型不匹配:不能从元素类型对象转换为int

htLinkedHashMap

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); 
    } 
} 
+0

我不是确定这是Java中有效的_for_语句。 [Java] for“loop”(http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html) – m0skit0

+0

@ m0ski0:从来没有听说过'for-each'? http://download.oracle.com/javase/1.5.0/docs/guide/language/foreach.html –

回答

4

您需要使用Java generics更好。

声明ht作为LinkedHashMap<Integer, Foo>其中Foo是您希望由ht.get()返回的任何数据类型。使用Map接口就更好了:

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

使用Integer而不是int,它可能会工作。 LinkedHashMap中的键必须是对象,而不是基元类型。

+3

我应该照顾自动装箱,我怀疑。 – aioobe

0

ht是LinkedHashMap,如果它只包含Integer s,则应声明它为LinkedHashMap<Integer,Object>

如果将声明为LinkedHashMap<Integer,Object>,则将自动拆箱到int

(*),即使你把它声明为LinkedHashMap<Integer,[actual-object-type]>

0

它必须是:for (Integer key : ht.keySet())...

LinkedHashMap<K, V>其中K和V为对象,而不是primitiv(INT,短...)

+0

在Java 1.5+中,自动装箱会照顾到这一点。真正的问题是缺乏泛型。 – MathSquared

相关问题