Next we'll get more practice working with interfaces.
We'll move past our friend Comparable
and look at two new Java interfaces that allow us to integrate with a built-in language feature—the enhanced for
loop.
Super cool!
Let's go...
Iterable
and Iterator
Now let's have more fun with interfaces.
Remember the enhanced Java for
loop:
So it turns out that we can implement our own classes that can be used in the enhanced for
loop.
Pretty cool!
Let's look at the interfaces that are required and consider how they work.
We'll examine them both at once, since they are really designed to work together:
Now let's put what we know to use to build a simple random number generator.
We'll create a class that can be used on the right side of a for
loop and generates a certain number of random int
values.
Next, let's look at a few improvements to our iterable random number generator based on what we've already done.
Need more practice? Head over to the practice page.