Iterator Look at each element in v Iterator

  • Slides: 7
Download presentation
Iterator – Look at each element in ? ? ? v Iterator is an

Iterator – Look at each element in ? ? ? v Iterator is an interface q v Something that is an Iterator must have the methods: q q v v (This concept is similar to the idea of an abstract class) has. Next() next() Look at the API Used in the following pattern: while(? ? ? . has. Next()) { var = ? ? ? . next(); //do something with var } Don’t know the order of the elements Guaranteed to give you all the elements in the related set of information Comp. Sci 6 20. 1

Iterator v Can’t use an iterator with an array. Why? q What’s wrong with

Iterator v Can’t use an iterator with an array. Why? q What’s wrong with this picture? : int[] m = new int[n]; fill. With. Data(m); while (m. has. Next()) {. . . q Comp. Sci 6 20. 2

How do we create an Iterator? v For Collections such as Array. Lists one

How do we create an Iterator? v For Collections such as Array. Lists one can get an interator using the interator method: // You must create iterator for Array. List // Assume an Array. List<String> named words Iterator<String> iter = words. iterator(); // Now use iterator to print elements in words while (iter. has. Next()) { System. out. println(iter. next()); } Comp. Sci 6 20. 3

Some classes implement Iterator v Look at the Scanner API q It includes the

Some classes implement Iterator v Look at the Scanner API q It includes the required methods: o has. Next() o next() q Also provides many in the same vein, for example: o has. Next. Int() o next. Int() o has. Next. Line() o next. Line() o etc. Comp. Sci 6 20. 4

For each in Java 5 v In many cases, can replace iterator with for-each

For each in Java 5 v In many cases, can replace iterator with for-each loop // Assume an Array. List<String> named words // No need to get iterator // directly use loop for (String s: words) { System. out. println(s); } Comp. Sci 6 20. 5

For each in Java 5 v BONUS: it also works for Arrays // Assume

For each in Java 5 v BONUS: it also works for Arrays // Assume an array Sring[] named words // directly use loop for (String s: words) { System. out. println(s); } Comp. Sci 6 20. 6

When can I use for-each? v Must be an array or a class that

When can I use for-each? v Must be an array or a class that implement the Iterable interface q q Loop up API for Iterable What method must an Iterable class have? Comp. Sci 6 20. 7