【问题标题】:How do I use Iterator from within a function?如何在函数中使用迭代器?
【发布时间】:2014-11-17 19:22:29
【问题描述】:

我试图通过一些示例来了解 Java 中的迭代器功能,但我不知道如何访问迭代器以便开始打印集合。

所以我有这个功能:

class A <Item> implements Iterable <Item> {
   //....does stuff
}

public Iterator <Item> iterator() {
   return new Itor();
}

class Itor implements Iterator <Item> {
  //.....custom Iterator functions within
}

基本上,类 A 是一个包含值列表的数据结构,我想使用另一个类中的迭代器将这些值打印出来。我将如何实施?我不确定语法会是什么样子。

假设我还有一门课

class B {
    private class Node {
        A<Integer> n;      // I have another class that inserts values into the A class
                           // and I want to be able to print n out.                     
    }

    private void printA() {
        Iterator it = A.iterator(); //I get the non-static method error here.
    }
}

【问题讨论】:

  • 错误:When I try to declare the Iterator, I get Non-static method iterator() cannot be referenced from a static context. 请告诉我们导致错误的代码。我猜你可能在main() 中做错了什么。

标签: java printing iterator iterable


【解决方案1】:

假设你的类实现了“迭代器”,那么你的类的客户端就简单了

1) 调用Iterator it = myInstance.iterator();(或者,更好的是,调用Iterator&lt;SomeClass&gt; it = myInstance.iterator();

2) 循环调用it.hasNext()(查看是否有剩余对象),最后

3) 在该循环内调用myObject = it.next()(以获取对象)

这是一个很棒的教程(Mkyong 的教程所有都很棒,IMO ;)):

http://www.mkyong.com/java/how-do-loop-iterate-a-list-in-java/

【讨论】:

  • 当我尝试声明迭代器时,我得到非静态方法 iterator() 不能从静态上下文中引用。
  • 请向我们展示发生这种情况的示例代码。
【解决方案2】:

// 干净编译

import java.util.*; 

class A {   
  public List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 
}

public class B {
  public Iterator<String> iterator;

  public static void main(String[] args) {
    A a = new A();
    B b = new B();
    b.iterator = a.list.iterator();
    while(b.iterator.hasNext()) {
      System.out.println(b.iterator.next());
    }   
  } 
}

【讨论】:

    【解决方案3】:

    想通了,就是这么简单

    for (Integer n : Node.n) {
        System.out.println(n);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2014-10-05
      • 1970-01-01
      • 2020-04-03
      • 2020-10-29
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多