【问题标题】:How is it possible to use the for-each loop for classes that do not implement Iterable对于不实现 Iterable 的类,如何使用 for-each 循环
【发布时间】:2015-09-21 03:33:24
【问题描述】:

我正在阅读 The Complete Reference 的集合,然后我遇到了这个声明

集合界面

集合接口是集合的基础 构建框架是因为它必须由任何类实现 定义一个集合。 Collection 是一个通用接口,它有这个 声明:interface Collection<E>。这里,E 指定类型 集合将持有的对象。集合扩展了 Iterable 接口。这意味着所有集合都可以通过 使用 for-each 样式的 for 循环。(回想一下,只有那些 实现Iterable可以通过for循环)。

最后两行写着只有那些实现了Iterable接口的类才能循环通过for循环。 但是,我猜对象类没有实现可迭代接口,那么我们如何在字符串、整数等情况下使用 for-each 循环。

【问题讨论】:

  • Recall that only classes that implement Iterable can be cycled through by the for. 还有数组,别忘了数组。

标签: java collections foreach interface iterable


【解决方案1】:

确实如此。 java.lang.Object 没有实现Iterable<T> 接口。

我们可以遍历对象,因为对象持有者(例如Collection)自动实现Iterable<T>,不一定是集合的对象部分。

【讨论】:

  • @Crazyjavahcking-哦,,,知道了,伙计。
  • 为什么有这么多粗体字?
【解决方案2】:

如果您正在遍历字符串或整数的集合,则 collection 是可迭代的,而不是字符串或整数。迭代中的项目不必是可迭代的;容器可以。

【讨论】:

    【解决方案3】:

    你永远不会想要遍历一个整数,也永远不会做这样的事情。整数是单个实体,而可迭代接口是指实体集合。例如:

    List<Integer> intList = new ArrayList<Integer>();
    
    for (Integer i : intList) {
       System.out.println(i);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 1970-01-01
      • 2021-07-09
      • 2021-03-05
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多