Re: Generics - Is this possible?
On Tue, 15 Apr 2008 16:41:55 -0700, Patricia Shanahan <pats@acm.org> wro=
te:
I certainly agree that not allowing user code access to the actual
iterator would be desirable, if it were possible. It isn't.
But it would be if Java supported using an Iterator in the for() stateme=
nt.
The
following, horrible, program prints "1", then "3", then gets a
java.util.NoSuchElementException.
Right. But if you can provide an actual iterator in the for() statement=
, =
then the code has access to the iterator implicitly. It wouldn't be =
nearly so much work to reproduce the example of bad usage you provided i=
f =
Java allowed an Iterator instead of an Iterable implementation in the =
for() statement. Your example would instead look like this:
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class WildFor {
public static void main(String[] args) {
List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5);
Iterator<Integer> myIterator = myList.iterator();
for (Integer i : myIterator) {
myIterator.next();
System.out.println(i);
}
}
I don't know if that's why Java doesn't allow that, but it sure seems li=
ke =
a good enough reason to me. :)
Pete