How do I use Iterator from within a function?

520 Views Asked by At

I'm trying to get my mind around the Iterator functionality in Java through some examples, and I can't figure out how to access the iterator so that I can start printing out the collection.

So I have this function:

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

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

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

Basically, class A is a data structure that holds a list of values, and I want to print these values out using iterator from within another class. How would I implement that? I'm not sure on how the syntax would look like.

Let's say I have another class

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.
    }
}
3

There are 3 best solutions below

0
On BEST ANSWER

Figured it out, it was something as simple as

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

Assuming your class implements "Iterator", then the client of your class simply

1) calls Iterator it = myInstance.iterator(); (or, better, calls Iterator<SomeClass> it = myInstance.iterator();,

2) calls it.hasNext() in a loop (to see if there are any objects remaining), and finally

3) calls myObject = it.next() inside that loop (to fetch the object)

Here is a great tutorial (Mkyong's tutorials are all great, IMO ;)):

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

0
On

// clean compiled

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