【问题标题】:When to use Iterable, when to use Iterator? [duplicate]什么时候用Iterable,什么时候用Iterator? [复制]
【发布时间】:2014-04-29 22:19:19
【问题描述】:

我必须实现类Incrementer,它假设实现Iterable 我真的不明白为什么它应该实现Iterable<Integer> 而不是Iterator<Integer>?我不要求仅使用接口的解决方案。

为什么in(int,int) 方法是静态的?

public class Test {

  public static void main(String[] args) {

    for(int k : in(1, 10)) System.out.print(k + " ");
    System.out.println();

    for(int k : in(1, 10).by(2)) System.out.print(k + " ");
    System.out.println();

    for(int k : in(10, 1)) System.out.print(k + " ");
    System.out.println();


    for(int k : in(1, 10).by(-1)) System.out.print(k + " ");
    System.out.println();

    Incrementer inc;
    for (int i : inc = in(1,10) ) {
      if (i == 4) inc.by(2);
      System.out.print(i + " ");
    }
    System.out.println();
    for (int i : inc = in(1,10) ) {
      if (i == 8) inc.by(-2);
      System.out.print(i + " ");
    }
    System.out.println();
    for(int k : inc = in(10, 1)) {
      if (k == 5) inc.by(1);
      System.out.print(k + " ");
    }

  }  
}

输出:

1 2 3 4 5 6 7 8 9 10 
1 3 5 7 9 
10 9 8 7 6 5 4 3 2 1 
10 9 8 7 6 5 4 3 2 1 
1 2 3 4 6 8 10 
1 2 3 4 5 6 7 8 6 4 2 
10 9 8 7 6 5 6 7 8 9 10

【问题讨论】:

  • 如果你不实现Iterable,你就不能像现在这样在foreach循环中使用你的类。

标签: java iterator iterable


【解决方案1】:

Iterable 类有一个方法iterator(),它返回一个Iterator 类的实例,可以用来迭代对象。一旦你有Iterator 类实例,你可以使用hasNext()next() 方法迭代你的类中的元素

【讨论】:

  • 谢谢,但是我应该在哪里保留字段 val 代表 Integer 在实现 IteratorIterable 的类中?
  • 这个界面最明显的变化是它允许在foreach循环中使用
  • 为什么in(int,int)方法是静态的?
  • +1 给您的评论,将此作为答案发布
  • @fge 这是一个强项,这是我们应该实现 Iterable 而不是直接处理 Iterator 实例的唯一原因。因此,您应该将这一点作为单独的答案发布,包括 for each 的概念循环
【解决方案2】:

在设计一个类时,如果我们想提供迭代器功能,我们会实现 Iterable 接口。现在 Iterable 接口有方法 Iterator<T> iterator() 所以你需要在你的类中编写迭代器的实现。

您应该查看集合类的源代码(实现集合接口),它们具有相同的实现。

所以基本上你需要使用这两个接口来在你的类中提供迭代器功能。

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 2010-09-11
    • 2011-09-28
    • 2014-03-27
    • 2013-10-19
    • 1970-01-01
    • 2012-08-07
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多