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

2.12 Shuffling the Integer Array

Juppies 2 by Dr Heinz M. Kabutz

We learn a good technique for creating new methods. Simply write into your code the name of the method and the parameters that you will send it, in our case shuffle(indexes). Our IDE immediately recognises that this method does not exist yet and marks it. We can now click on the error and press our magic ALT+Enter button (Option+Enter on Mac, Control+0 in Eclipse). This saves us a lot of typing.

The shuffle method works like this. We start with the last element and swap it with one of the elements on the left, including the element itself. The nextInt() method takes a bound and the result is always from 0 up to excluding the bound. Thus, if we ask for nextInt(10), we will get a number from 0 to 9. This is why we always include the current index in the random number generation by calling nextInt(i + 1). Otherwise, it would be impossible for the last element to stay the same, which would then not be as random as we probably want.

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.