couldn't help but feel the title is kinda vague, sorry about that. I couldn't describe it better.
I'll get a little more into detail; I'm trying to figure out how to get an iterator working the way I want it to outside of the class it's implemented in. I couldn't manage to find any information on my problem. This is part of an assignment for University, AlphaTest.java should be left as is.
I have a class, Alpha, which holds a class which follows the doubly linked list principle, Bravo. Bravo holds the link to the previous and next instance in the list.
I want to be able to iterate through the linked list with an iterator implemented in the Alpha class so that I can easily go through each instance using a for loop like this:
for(Bravo b: alphaInstance) {...}
.
I got this to work as intended within the Alpha class itself, but once I try the same outside of the Alpha class, in AlphaTest for example, it doesn't work as intended. Once I try that I'm hit with the following error:
Error:(220, 23) java: incompatible types: java.lang.Object cannot be converted to models.Bravo
It wants me to instantiate the instance as an Object like so:
for(Object o: alphaInstance) {...}
I could of course cast the object to Bravo. But that's not part of the assignment.
See code below to see what's going wrong. The problem can be found in AlphaTest.java
.
Alpha.java
class Alpha<E extends Bravo> implements Iterable<Bravo> {
Bravo head;
public Alpha(Bravo head) {
this.head = head;
}
public void example() {
for(Bravo b: this) {
// This works, it's succesfully recognized as an instance of Bravo.
}
}
@Override
public Iterator<Bravo> iterator() {
return new BravoIterator(this.head);
}
private class BravoIterator implements Iterator<Bravo> {
private Bravo currentBravo;
public BravoIterator(Bravo head) {
this.currentBravo = head;
}
@Override
public boolean hasNext() {
return this.currentBravo != null;
}
@Override
public Wagon next() {
Bravo data = this.currentBravo;
this.currentBravo = this.currentBravo.getNextBravo();
return data;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
AlphaTest.java
{...}
@BeforeEach
private void setup() {
// Assume this is a doubly linked list
Bravo bravo = new Bravo(...);
instanceOfAlpha = new Alpha(bravo);
}
public T1_checkImplementationOfIterableInterface() {
for(Bravo b: instanceOfAlpha) { // <---------------------------------------------[This is the problem]
// This does not work, it expects an instance of Object.
}
}
{...}