Question

I have to implement class Incrementer and it suppose to implement Iterable I do not really get why it should implement Iterable<Integer> instead of Iterator<Integer>? I do not ask for solution just the usage of Interfaces.

Why the method in(int,int) is static?

public class Test {

  public static void main(String[] args) {

    for(int k : in(1, 10)) System.out.print(k + " ");
    System.out.println();

    for(int k : in(1, 10).by(2)) System.out.print(k + " ");
    System.out.println();

    for(int k : in(10, 1)) System.out.print(k + " ");
    System.out.println();


    for(int k : in(1, 10).by(-1)) System.out.print(k + " ");
    System.out.println();

    Incrementer inc;
    for (int i : inc = in(1,10) ) {
      if (i == 4) inc.by(2);
      System.out.print(i + " ");
    }
    System.out.println();
    for (int i : inc = in(1,10) ) {
      if (i == 8) inc.by(-2);
      System.out.print(i + " ");
    }
    System.out.println();
    for(int k : inc = in(10, 1)) {
      if (k == 5) inc.by(1);
      System.out.print(k + " ");
    }

  }  
}

Output:

1 2 3 4 5 6 7 8 9 10 
1 3 5 7 9 
10 9 8 7 6 5 4 3 2 1 
10 9 8 7 6 5 4 3 2 1 
1 2 3 4 6 8 10 
1 2 3 4 5 6 7 8 6 4 2 
10 9 8 7 6 5 6 7 8 9 10
Était-ce utile?

La solution

Iterable class has a method iterator() which returns an instance of Iterator class which can be used to iterate objects.Once you have Iterator class instance,you can use hasNext() and next() methods to iterate the elements in your class

Autres conseils

While designing a class if we want to provide iterator functionality , we implement Iterable interface. Now Iterable interface has method Iterator<T> iterator() so u need to write implementation of iterator inside your class.

You should look at source code of collection classes ( which implements Collection Interface ) they have same kind of implementation.

So basically you need to use both interfaces to provide iterator functionality in your class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top