Enhanced for-loop does not accept Iterator

Sorry if this was asked before. My search did not raise any other similar questions. This surprised me in Java.

Apparently the extended for-loop only accepts an array or instance of java.lang.Iterable . It does not accept a java.util.Iterator as a valid obj reference to iterate over. For example, Eclipse displays an error message for the following code. It says: " It can only iterate over an array or an instance of java.lang.Iterable "

 Set<String> mySet = new HashSet<String>(); mySet.add("dummy"); mySet.add("test"); Iterator<String> strings = mySet.iterator(); for (String str : strings) { // Process str value ... } 

Why is this so? I want to know why the advanced for-loop was designed this way. Although Iterator is not a collection, it can be used to return one item at a time from the collection. Note that the only way in the java.lang.Iterable interface is Iterator<T> iterator() , which returns an Iterator . Here I directly pass it to Iterator . I know that hasNext() and next() can be used, but using the extended for loop makes it cleaner.

Now I understand that I could use the extended for loop directly above mySet . Therefore, I do not need an extra call to get an Iterator . So this will be a way to encode it, and yes - it really makes sense.

+5
source share
4 answers

The extended for loop was part of JSR 201 . From this page you can download the proposed final draft documents, which include a FAQ section that directly addresses your question:

Appendix I. Design FAQs

  • Why can't I use the extended for statement with an Iterator (rather than an Iterable or an array)?

Two reasons: (1) The construct will not greatly contribute to syntactic improvement if you have an explicit iterator in your code and (2) The execution of the loop will have a โ€œside effectโ€ of promoting (and usually depleting) the iterator. In other words, the extended for statement provides a simple, elegant solution for the usual case of iterating over a collection or an array, and does not try to solve more complex cases that are better addressed to the traditional ones for approval.

  1. Why can't I use the extended statement for:
    • delete items when moving a collection ("filtering")?
    • iterate over multiple collections or arrays at the same time?
    • change current slot in array or list?

See paragraph 1 above. An expert group reviewed these cases, but chose a simple, clean extension that the dose (sic) is good. the design obeys the โ€œ80-20 ruleโ€ (it handles 80% of cases with 20% effort). If the case falls into another 20%, you can always use an explicit iterator or index, as you did in the past.

In other words, the committee decided to limit the scope of the proposal, and some of the functions that could be presented as part of the proposal did not reduce.

+4
source

The extended for loop was introduced in Java 5 as an easier way to iterate over all elements of a collection [or array].

http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/enhanced-for-loops.html

An iterator is not a collection of elements,

This is an object that allows the programmer to move around the container. An iterator can be thought of as a type of pointer.

https://en.wikipedia.org/wiki/Iterator

Thus, those improved for loops work by looking at all the elements in the structure containing the elements, while the iterator does not contain the elements, it looks more like a pointer.

+6
source

In your example, you are creating an iterator but not using it correctly. As for the answer to your question about why the exception is thrown - it is from the line:

  for (String str : strings) { 

"strings" is an iterator, not a collection that you can scroll through. Thus, you have several options that you can iterate through the set using an extended loop:

 for(String myString : mySet){ //do work } 

or you can iterate through the set using an iterator:

 Iterator<String> strings = mySet.iterator(); while(strings.hasNext()){ //do work } 

hope you find this helpful.

+1
source

The error occurs because you are trying to iterate through an Iterator , not a List or Collection . If you want to use Iterator , I recommend using its next () and hasNext () :

 Set<String> mySet = new HashSet<String>(); mySet.add("dummy"); mySet.add("test"); Iterator<String> strings = mySet.iterator(); while(strings.hasNext()){ String temp = strings.next(); System.out.println(temp); } 
0
source

All Articles