Running on Java 17+35-2724 (Preview)
Home of The JavaSpecialists' Newsletter

2.8 Integer Array for Shuffled Indexes

Juppies 2 by Dr Heinz M. Kabutz

We want to shuffle the words in the other WordLibrary, but how? The way I recommend we do it is by having an int array that contains the shuffled index. For example, say we have a WordList with 5 words. We thus create an int[] {0, 1, 2, 3, 4}. We then shuffle that, resulting in, for example, int[] {4, 1, 0, 2, 3}. We can now consistently map the correct and the scrambled word to the correct index in our WordLibrary. If someone calls getWord(2), we return getWord(0) (picking the new index from our shuffled array).

Note that we typically write the for-loops over arrays with an int index called "i", and going up to less than the array.length. Even though we use the getSize() of the other WordList to create the array, once we have created it, we only use array.length for the size. This makes the code easier to change in future, in case we want to only use a subset of the other WordList then we only have to change one place - where we create the array - rather than having to also change the for loop.

Comments

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.



About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack 21

Superpack 21 Our entire Java Specialists Training in one huge bundle more...

Free Java Course

Free Juppies 2 Course
Juppies 2 - a course for complete beginners more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.