2011-08-18 129 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

相關問題