Reputation: 3154
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
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
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
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