MBrown
MBrown

Reputation: 593

Running through the elements in an iterator, then calling the methods?

In one file i have this:

public DirectoryNode(String n, List<FileSystemNode> c) {
...
private List<FileSystemNode> nodes;
...
public Iterator<FileSystemNode> iterator() { return nodes.iterator(); }
...}

And in another file, I have this:

public class SizeVisitor implements FileSystemVisitor<Integer>
{...
    public Integer visitDirectory(DirectoryNode d){
    }
}

My question is, how do I, in the visitDirectory make a for loop, which will take the iterator for d, and go through all the elements, and then on each element call the method "getSize", which is implemented in FileSystemNode? Thanks you very much for your help.

Upvotes: 0

Views: 1044

Answers (2)

micha
micha

Reputation: 49572

Someting like this:

public Integer visitDirectory(DirectoryNode d){
 Iterator<FileSystemNode> i = d.iterator();
 while (i.hasNext()) {
   FileSystemNode fsn = i.next();
   fsn.getSize()
 }
}

If you implement the Iterable interface in DirectoryNode you can also use a for-each loop:

public Integer visitDirectory(DirectoryNode d){
  for (FileSystemNode fsn : d) {
    fsn.getSize()
  }
}

Upvotes: 1

Wim Deblauwe
Wim Deblauwe

Reputation: 26858

You might want to do something like this:

public Integer visitDirectory (DirectoryNode d) {
  for ( Iterator<FileSystemNode> iterator = d.iterator(); iterator.hasNext(); ) {
    FileSystemNode fsn = iterator.next();
    fsn.getSize();
  }
}

You can also make your DirectoryNode implement the Iterable interface so you can use the foreach loop:

public Integer visitDirectory (DirectoryNode d) {
  for ( FileSystemNode fsn : d) {
    fsn.getSize();
  }
}

Upvotes: 1

Related Questions