Kotlin
Java

Practice with Interfaces
Java

Created By: Geoffrey Challen
/ Updated: 2021-10-06

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:

Provide an overview of the Iterator and Iterable interfaces.

Random Number Iterator

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.

Create a class that iterates over a set of a fixed number of random values.

A Few Improvements

Next, let's look at a few improvements to our iterable random number generator based on what we've already done.

Provide a way to reset the instance so it can be reused. And briefly discuss generics.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough