Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 800
sp00m Avatar asked May 29 '12 15:05

sp00m


3 Answers

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();
   }
}
like image 154
Hovercraft Full Of Eels Avatar answered Nov 11 '22 09:11

Hovercraft Full Of Eels


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();
like image 28
Wormbo Avatar answered Nov 11 '22 09:11

Wormbo


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.

like image 36
Edwin Dalorzo Avatar answered Nov 11 '22 10:11

Edwin Dalorzo