Iterator <T> returns an object

I wrote a simple class:

public class Report<T> implements Iterable {
  private ObservableList<T> items = FXCollections.observableArrayList();
  // ...

  public ObservableList<T> getItems() {
    return items;
  }

  public Iterator<T> iterator {
    return items.iterator();
  }

  //  ...
}

But when I try to use a foreach loop like this, I get the error Incompatible types:

Report<FinRecord> report = new Report<>()
for (FinRecord r : report) {
    // ...
}

This code works fine, but I need cleaner code, and I don't understand why the previous code returns Object.

for (FinRecord r : report.getItems()) {
    // ...
}    

Is this a feature of java, so it creates Iteratornot Iterator<T>or am I missing something?

+3
source share
1 answer

Your class should implements Iterable<T>.

public class Report<T> implements Iterable<T>
{
  private ObservableList<T> items = FXCollections.observableArrayList();
  // ...

  public ObservableList<T> getItems() {
    return items;
  }

  public Iterator<T> iterator() {
    return items.iterator();
  }

  //  ...
}
+9
source

All Articles