CS 231: Lab #1

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.

Documentation for Java 1.5 is located at: Java 1.5 SE API.

Documentation for Java 1.6 is located at: Java 1.6 SE API

If using a terminal is new to you, or you need a refresher, please check out the Terminal tutorial.

Tasks

  1. Create a working directory for today's lab. Then start a Java file called Lab1Test.java.
  2. Import the ArrayList and Random classes into your file.

    import java.util.ArrayList
    import java.util.Random

  3. Create a class Lab1Test that has a main function only.

    public static void main( String args[] )

  4. In your main function, declare and allocate a new ArrayList object and a new Random object. Then use a for loop to add ten 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.
  5. Loop through your ArrayList, get each value in turn and print it out using System.out.println. Note that the ArrayList get function returns an Object which you will need to cast to an Integer type for it to print out properly.
  6. Loop 10 times and randomly remove one 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 us System.out.print to 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.
  7. 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.

Once you are comfortable with building classes and using an ArrayList, go on to the assignment.