sp00m
sp00m

Reputation: 48837

Arrays, lists, sets and maps are iterable. What else?

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?

Upvotes: 6

Views: 12663

Answers (4)

Wormbo
Wormbo

Reputation: 4992

Only classes implementing the Iterable interface and arrays are. Maps do not implement Iterable, instead they provide three different iterable views (key set, value collection and entry set), which you can iterate over. A more complete check would thus be:

return obj instanceof Iterable || obj.getClass().isArray();

Upvotes: 6

Puce
Puce

Reputation: 38142

Apart from Iterables also arrays (which don't implement the Iterable interface) can be used in the enhanced for loop.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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

class Person {
   private String lastName;
   private String firstName;
   public Person(String lastName, String firstName) {
      this.lastName = lastName;
      this.firstName = firstName;
   }
   @Override
   public String toString() {
      return "Person [lastName=" + lastName + ", firstName=" + firstName + "]";
   }


}

MyPeople.java

class MyPeople implements Iterable<Person> {
   List<Person> personList = new ArrayList<Person>();

   // ... other methods and constructor

   @Override
   public Iterator<Person> iterator() {
      return personList.iterator();
   }
}

Upvotes: 17

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78639

The JDK 1.7 Documentation in the Iterable interface lists everything within the JDK API that implements iterable, but nothing precludes a third-party library from implementing Iterable as well in any class.

Upvotes: 3

Related Questions