本文介绍了数组,列表,集合和映射是可迭代的.还有什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使仅ListSet实现接口Iterable,我相信数组,列表,集合和映射都是 iterable 对象,因为我们可以通过foreach循环使用它们:

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());

Map的情况可能有所不同,但可以将其视为键值列表(实际上是键值列表).

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;
}

换句话说,是否还有其他类型可以通过foreach循环进行迭代?

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?

推荐答案

任何实现Iterable<T>接口的都是可迭代的. Iterable API 列出了许多核心Java执行此操作的类.并请注意,这还包括您创建的用于实现接口的类.如果我的类包含ArrayList或其他可迭代对象,而我想方便地迭代其内容,则有时会这样做.我只是将列表的Iterator对象传递为iterator()方法的返回结果.

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.

例如:

Person.java

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

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

这篇关于数组,列表,集合和映射是可迭代的.还有什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 00:07