O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Iterate Through Collection Items in Random Order

Problem

You need to enumerate through all the items in a collection, but you don’t want to visit items in order.

Solution

Create the RandomIterator class shown below, and use it to store an ArrayList of randomly ordered items.

Discussion

By default, enumeration moves through the items of a collection in order from first to last. And while it’s easy to randomly select a single item in a collection using the Random class, it’s more difficult to randomly walk through all items in a collection and ensure that each one is visited only once.

The solution is the RandomIterator class shown below. It stores a private collection and inserts all items into that collection in a random order. You can then walk through ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required