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) {
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.
source share