2015-10-30 79 views
0

我有这样一段代码:的foreach循环语法错误

private V[] elements; 

public int size(){ 
    int returnValue = 0; 
    for(TableEntry<K,V> pointer : elements){ 
    while(pointer != null){ 
     returnValue++; 
     pointer = pointer.next; 
    } 
    } 
    return returnValue; 
} 

我得到错误:

Type mismatch: cannot convert from element type V to SimpleHashtable.TableEntry in foreach line.

下面是完整的类:Code

+2

元素是'V',不是的'TableEntry '数组的数组... – assylias

+0

是TableEntry哈希表的一些子类? – Gacci

+0

你的问题不是关于for循环,而是关于你如何在你的代码中混合使用V和TableEntry。您需要选择其中一个或另一个...... – assylias

回答

4

您正试图获得TableEntry对象来自Velements)的阵列。这不起作用。

另外,对于数组中的每个条目,您的循环都是双倍的,您尝试搜索数组的其余部分。

尝试此代替:

public int size() { 
    int returnValue = 0; 
    for (V pointer : elements) 
     if (pointer != null) { 
      returnValue++; 
     } 
    return returnValue; 
} 
0

变化指针变量的类型V

for (V pointer : elements) { 
    \\ loop body 
} 
+1

'V'不必实现'Iterable',他正在迭代不超过'V'的数组。请参阅[JLS 14.14.2](https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2)。 – Tomas

+0

哦,是的!错过了'[]',谢谢:) –