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

Even if List, and Setimplement an interface Iterable, I believe that array, list, set and map - it's all istrebimye objects, because we can use them all through the 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 with Mapmay be a little different, but consider it as a list of key values ​​(what it really is).

Starting from this iterative understanding, is there a lack of 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 repeated through the foreach loop?

Side, but the resulting question: is the list of exhaustive types?

+5
source share
4 answers

, Iterable<T>, . Iterable API Java, . , , . , ArrayList , , . Iterator iterator().

:

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();
   }
}
+15

, Iterable . Iterable, ( , ), . , :

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

The JDK 1.7 documentation in the Iterable interface lists everything in the JDK API, which implements iteration, but does not exclude a third-party library from Iterable, as well as in any class.

+3
source

In addition to Iterables, arrays (which do not implement the Iterable interface) can also be used in an extended loop.

+1
source

All Articles