user2953119
user2953119

Reputation:

Do I really need to implement iterator in that case?

I need some advice about usage of Iterable<T> in Java.

I have the following class:

public abstract class Validator implements Comparable<Validator>{
    public abstract boolean validate();
    public abstract int getPriority();

    @Override
    public int compareTo(Validator o) {
        return getPriority() > o.getPriority() ? -1 :
                getPriority() == o.getPriority() ? 0 : 
                    1;
    }
}

I need to create a class ValidatorChain as follows:

public class ValidatorChain{
    //Contains Collection<Validator>

    // and we can iterate over it with for-each loop in high-to-low priority order
}

Maybe I should just override some instant implementation of Iterable<T> instead of writing my own one from scratch.

Upvotes: 5

Views: 86

Answers (2)

assylias
assylias

Reputation: 328568

You can write it manually in a simple way by delegating to the collection's iterator:

public class ValidatorChain implements Iterable<Validator> {
  Collection<Validator> validators = ...;
  public Iterator<Validator> iterator() {
    return validators.iterator();
  }
}

If you need it sorted, you can either sort the validators collections or take a copy:

  public Iterator<Validator> iterator() {
    List<Validator> sorted = new ArrayList<> (validators);
    Collections.sort(sorted);
    return sorted.iterator();
  }

Or with Java 8:

 public Iterator<Validator> iterator() {
    return validators.stream().sorted().collect(toList()).iterator();
  }

Upvotes: 5

maskacovnik
maskacovnik

Reputation: 3084

You can only extends your ValidatorChain with a collection:

public class ValidatorChain extends ArrayList<Validator>{
    //...
}

Now it is iterable, because of extending ArrayList which is iterable itself

Upvotes: 3

Related Questions