Bonjour la compagnie
J'aimerai savoir quand est-ce qu'on utilise un iterator ?
On l'utilise seulement pour parcourir une liste ?
Merci
Version imprimable
Bonjour la compagnie
J'aimerai savoir quand est-ce qu'on utilise un iterator ?
On l'utilise seulement pour parcourir une liste ?
Merci
Pour parcourir une Collection de manière générale... Sans avoir à connaitre l'implémentation de ta collection.
Bref, un outil commun de parcours des éléments d'une Collection (List, ArrayList, Set, Queue, etc...)
Salut,
Un Iterator sert à itérer. Tous ce qui est Iterable (implémente Iterable, et les tableaux, cas particulier sur lequel on peut faire un foreach) fournit un Iterator. Les classes qui implémentent List sont Iterable, mais c'est un cas parmi d'autres.
On peut tout à fait faire :
AvecCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 public class IntIterator implements Iterator<Integer>, Iterable<Integer> { private final int start; private final int end; private int current; public IntIterator(int start, int end) { this.start=start; this.end=end; this.current=start; } public Iterator<Integer> iterator() { return new IntIterator(start, end); } @Override public Integer next() { if ( current<=end ) { return current++; } throw new NoSuchElementException(); } @Override public boolean hasNext() { return ( current<=end ); } }
qui affiche :Code:
1
2
3
4
5
6
7
8 public static void main(String[] args) { for(int value : new IntIterator(10, 20)) { System.out.println(value); } }
Pas de liste ici.10 11 12 13 14 15 16 17 18 19 20
on peut même faire :
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 public class FibonacciIterator implements Iterator<Integer>, Iterable<Integer> { private final int max; private int current; private int value0=0; private int value1=1; public FibonacciIterator(int max) { if (max<0) throw new IllegalArgumentException(); if ( max>47 ) throw new ArithmeticException("max must be lesser than 48"); this.max=max; current = 0; } @Override public Iterator<Integer> iterator() { return new FibonacciIterator(max); } @Override public boolean hasNext() { return current<max; } @Override public Integer next() { if ( current>=max ) throw new NoSuchElementException(); final int next; switch( current ) { case 0: next = value0; break; case 1: next = value1; break; default: next = value0 + value1; value0=value1; value1=next; } current++; return next; } public static void main(String[] args) { for(int i : new FibonacciIterator(47)) { System.out.println(i + " "); } } }