Even if only List and Set implement the interface Iterable, I believe that an array, a list, a set and a map are all iterable objects, in that we can use them all through a foreach loop:
for(String s : new String[0]);
for(String s : new ArrayList<String>());
for(String s : new HashSet<String>());
for(Entry<Integer, String> entry : new HashMap<Integer, String>().entrySet());
The case of Map is maybe a bit different, but let consider it as a key-value list (what it actually is).
Starting with that iterable understanding, am I missing a type in the following method?
public boolean isIterable(Object o) {
return o instanceof Object[] || o instanceof Iterable || o instanceof Map;
}
In other words, are there any other types that can be iterated through a foreach loop?
Side but resulting question: is that list of types exhaustive?
Anything that implements the
Iterable<T>interface is iterable. The Iterable API lists many of the core Java classes that do this. And note that this also includes class that you create that implement the interface. I’ve done this at times if my class contains an ArrayList or other iterable object and I want to conveniently iterate through the contents of this. I simply pass the list’s Iterator object as the return result for the iterator() method.For example:
Person.java
MyPeople.java