Reputation: 51
I'm trying to make a list that is iterable and I'm stuck in the iterator part
this is my code
import java.util.Iterator;
public class MappableList<T> implements Iterable<T> {
T list[];
public MappableList(T arg1, T arg2, T arg3, T arg4) {
list = (T[]) new Object[4];
list[0] = arg1;
list[1] = arg2;
list[2] = arg3;
list[3] = arg4;
}
void printList() {
for (int i = 0; i < 4; i++) {
System.out.println(list[i]);
}
}
@Override
public Iterator<T> iterator() {
Iterator<T> iter = new list.iterator();
return iter;
}
}
it doesnt work at the part
Iterator<T> iter = new list.iterator();
any ideas or thoughts?
Thanks
Upvotes: 1
Views: 236
Reputation: 14077
Assuming your array is meant to be always entirely filled with elements, a minimal Iterator implementation could look like this:
@Override public Iterator<T> iterator()
{
final T[] list = this.list;
return new Iterator<T>()
{
int idx;
public boolean hasNext() { return idx < list.length; }
public T next() { return list[ idx++ ]; }
public void remove() { throw new UnsupportedOperationException(); }
};
}
By the way, you should consider to declare the list
member as private. Accessing it directly from places with knowledge about a narrower definition for type T (i.e. specialzed subclasses) could lead to ClassCastExceptions at runtime even though the code would compile fine with just a warning for the (T[])
cast you get in the contructor.
Upvotes: 0
Reputation: 17595
You have declared list
is an array, and as such it has no member iterator()
and less an inner class. iterator
to make an instance of.
You could implement your iterator index based where hasNext()
returns index < actIndex
and next()
returns list[itIndex]
and throws a NoSuchElementException
if it was called after hasNext()
returned false.
Upvotes: 0
Reputation: 198391
You need to actually reimplement the Iterator
interface; there's no such thing as list.iterator()
.
Upvotes: 2