Antonio Sesto
Antonio Sesto

Reputation: 3154

Iterable and Iterators - compile error

I have the following interface:

public interface DataSet<T> extends Iterable<T>  {
  public int nExamples();
  public T getExample(int index);
  public Iterator<T> iterator();
}

Then a class implementing this interface:

public class StringTupleDataset implements DataSet<StringTuple> {
Vector<StringTuple> examples;

public StringTupleDataset(Vector<StringTuple> examples) {
    if(examples == null) 
        throw new IllegalArgumentException("null parameter: examples");
    this.examples = examples;
} // constructor

@Override
public int nExamples() {
    return examples.size();
} // nExamples

@Override
public StringTuple getExample(int index) {
    return examples.get(index);
} // getExample

@Override
public Iterator<StringTuple> iterator() {
    return examples.iterator();
} // getAllExamples
} // class

The class StringTupleDataset compiles with no problem.

However, when I try and write this piece of code in another class:

public abstract class AbstractOntologyFiller<T> {
private AbstractOntologyFiller() {}

public static <T> void fill(OntologyManager ontoManager, DataSet<T> dataset) {
     for(T e : dataset.iterator()) {
          // do something
     } // for
  } // fill  
} // class

I have a compilation error saying:

Can only interate over an array or an instance of java.lang.Iterable

Is there anyone who can help me?

Upvotes: 0

Views: 183

Answers (3)

Antonio Sesto
Antonio Sesto

Reputation: 3154

Ok, got the error.

I should have written:

public static <T> void fill(OntologyManager ontoManager, DataSet<T> dataset) {
    for(T e : dataset) { // (without .iterator() 

Upvotes: 0

Andrew Spencer
Andrew Spencer

Reputation: 16484

You just need to iterate over dataset instead of dataset.iterator()

Explanation: the for loop is expecting an Iterable. The Iterable is not the iterator: it is the object that has the iterator() method on it.

Upvotes: 1

zw324
zw324

Reputation: 27180

You cannot iterate over an Iterator, but you can iterate through an Iterable.

for(T e : dataset)

will be enough, since Dataset extends Iterable, while dataset.iterator gives you an Iterator.

Upvotes: 4

Related Questions