I am building my own collection class implementing the Iterable interface in Java. However, I am getting a compilation error saying:
Nikolass-MacBook-Pro:week2 nburk$ javac Deque.java
Deque.java:115: error: incompatible types: Item#1 cannot be converted to Item#2
Item currentItem = current.item;
^
where Item#1,Item#2 are type-variables:
Item#1 extends Object declared in class Deque
Item#2 extends Object declared in class Deque.DequeIterator
1 error
Here are the relevant parts of my code:
public class Deque<Item> implements Iterable<Item> {
// return an iterator over items in order from front to end
public Iterator<Item> iterator() {
return new DequeIterator<Item>();
}
private class DequeIterator<Item> implements Iterator<Item> {
public DequeIterator() {
}
public Item next () {
Item currentItem = current.item; // this line causes the ERROR
current = current.next;
return currentItem;
}
}
}
I believe the issue somewhat is due to the fact that I am using the generics in a wrong way and my declaration of Item might not be correct. However, I was comparing my implementation with this quick tutorial and don't see any differences that might cause the issue on my side. Does anybody what I'm missing and how I can get rid of the error?
In
private class DequeIterator<Item> implements Iterator<Item> {
public DequeIterator() {
}
}
you're declaring a new type variable called Item. You aren't reusing the one declared with Deque<Item>. These may be different types. Instead, get rid of the parameter declaration
private class DequeIterator implements Iterator<Item> {
Presumably, current.item is a reference to an object of type Item declared in Deque, but you're trying to assign it to a variable of type Item declared in DequeIterator.
You'll also need to remove parameterizations of DequeIterator since it isn't generic any more. So, for example
return new DequeIterator<Item>();
changes to
return new DequeIterator();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With