The goal of this lab period is to get you started on the current assignment. In particular, we'll look at how to import and use the ArrayList class, one of the abstract data types provided by the standard library.
In the lab, we are have installed Java 1.8 (also referred to as Java Platform Standard Edition 8). You may have an older version on your computer (which is fine). Here are the links to the API's for the most recent versions:
If using a Terminal is new to you, or you need a refresher, please check out the Terminal tutorial.
- Make a new folder for this week's project.
- Start a Java file called Shuffle.java.
All Java files should include a comment header, describing the file name, the author, and the date, e.g.,
/** * File: Shuffle.java * Author: FirstName LastName * Date: MM/DD/YYYY */
Import the ArrayList and Random classes into your file.
import java.util.ArrayList; import java.util.Random;
Create a class Shuffle that has a main function only.
public static void main( String args )
In your main function, declare and allocate a new
ArrayList<Integer>object and a new
Randomobject. Then use a
addten random integers between 0 and 99 to your ArrayList. Look at the documentation for the Random class and the ArrayList class to figure out how. Have your loop print out the random numbers as they are generated (System.out.println()).
Note: ArrayLists are generic classes, which means they are designed to contain any type of object. The class is defined as
Eis a type variable. You will be making an ArrayList that should contain Integers, so you specify
Integerin place of
Loop through your ArrayList,
geteach value in turn and print it out using
System.out.println. Note that the ArrayList
getmethod returns an Object which you will need to cast to an Integer type if you want to store a reference to it.
Loop 10 times and randomly
removeone element from the ArrayList each time, printing out the value that was removed and the remaining values in the list (all on one line). You can use
System.out.printto send something to the command line without a newline. Note that you'll have to select a random number that is always strictly less than the number of elements left in the list.
- Change things around so that instead of assigning random numbers to the ArrayList in the beginning it assigns the values 1 through 10. Then run your program multiple times and look at its behavior.
- How can you programatically create a random permutation of a set of elements? Come up with two alternatives, and decide which is easier to program. In this week's assignment, shuffling a deck of playing cards involves creating a random permutation of the set of cards in the deck.
Once you are comfortable with building classes and using an
go on to the project.