0

I have this piece of code:

private V[] elements;

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

And I get error:

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

Here is complete class: Code

3
  • 2
    elements is an array of V, not an array of TableEntry<K, V>... Commented Oct 30, 2015 at 7:38
  • Is TableEntry some subclass of Hash table? Commented Oct 30, 2015 at 7:38
  • Your problem is not about the for loop, but about how you mix and cast between V and TableEntry in your code. You need to choose one or the other... Commented Oct 30, 2015 at 7:41

2 Answers 2

4

You are trying to get TableEntry objects from an array of V (elements). This will not work.

Also, your loop is double, for each entry in the array you try to search through the rest of the array.

Try this instead:

public int size() {
    int returnValue = 0;
    for (V pointer : elements)
        if (pointer != null) {
            returnValue++;
        }
    return returnValue;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change the type of pointer variable to V.

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

1 Comment

V doesn't have to implement Iterable, he is iterating over an array not over V. See JLS 14.14.2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.