CS102 Spring 2008

Lab # 3

Introduction to Generics, Collections, Iterators, and the For-Each loop

 

In this laboratory exercise you will implement a Main class that has a static method printList and a main method.  You will implement both of these methods according to the specification given below and use generic classes from the Framework of Collection classes, provided in the java.util library package, that implement the List interface.

 

The List Interface

 

The List interface in the java Collections framework contains the following operations (a partial list).  A more complete description is given on page 276 of the text.

 

            boolean add(E obj);

              // Apends the specified element to the end of the list

 

            void add(int index, E element);

              // Inserts the specified element at the specified position in this list

 

            boolean contains(Object obj);

              // Compares the specified object with this list for equality

 

            E get(int index);

              // Returns the element at the specified position in this list

 

            boolean isEmpty( )

              // Returns true if this list contains no elements

 

            Iterator<E> iterator( );

              // Returns an iterator over the elements in this list in proper sequence

 

            ListIterator<E> listIterator( );

              // Returns a list iterator of the elements in this list in proper sequence.

 

            E remove(int index);

              // Remove the element at the specified position in this list

 

            boolean remove(Object obj);

              // Remove the first occurrence in this list of the specified element

 

Iterator Operations

 

An Iterator<E> has methods (among others)

 

            boolean hasNext( );

              // Returns true if the iterator has more elements when traversing the list in the

              // forward direction

 

            E next( );

              // Returns the next element in the list

 

A ListIterator<E> contains the following additional methods

 

            boolean hasPrevious( );

              // Returns true if this list hyas more elements when traversing the list

              // in the forward direction

 

            E previous( );

              // Returns the previous element in the list

 

Launch NetBeans and Create Project

  1. Launch NetBeans and create a project named Lab3.  Go to the File menu and select "NewProject", then specify "Java Application" -- or click on the third button from the left on the button bar.
       
  2. Edit Main.java and add the following method to class Main:

       // prints elements in a collection using given iterator
       public static void printList(Iterator itr) {
           String outString = ...
           while (itr.hasNext()) {
               // some code using itr.next()
           }
           System.out.println(outString);
       }

    The above method is incomplete. We've given you a head start by providing you the structure for using the given iterator, but you must fill in the code to print the list, formatted according to the sample output below. You will need to import Iterator (or ListIterator) from java.util.)

  1. In the main() method you will declare two List variables, as follows:

        List<Integer> intList = new LinkedList<Integer>( );
        List<String> stringList = new ArrayList<String>( );

    List<Integer> indicates its type is  list of Integer objects; List<String> a list of String objects. Note the use of class Integer, not the primitive type int. Variable intList refers to a LinkedList implementation of a list of Integers; stringList refers to an array-based implementation of a list of Strings.

    Once you've entered these statements, you should see an indication of an error (a red "x") at the beginning of the line. This may be because you haven't told Java where the interface and classes are defined. Right-click on the red "x" and select th option to fix imports.
  2. Once you have declared and instantited these two lists you will initialize them as follows:
    1. use a for-loop to add the square of the integers from 1 to 10 inclusive to intList,
    2. Declare an array of String objects and initialize it with the following initialization list:
         
      {"Java", "is", "an", "object-oriented", "programming", "language", "that", "is", "fun", "to", "learn"}
         

      Use a for-loop to copy the elements of this array to stringList.
         
  3. Obtain an iterator from both of these lists and pass each of these iterators in turn to your printList() method. To help you get started, here's the code to obtain an Iterator from intList:
     
        Iterator<Integer> intIterator = intList.iterator();
       
  4. Iterators are nice, and generics permit us to reuse more code than we could before, but using iterators is a bit tedious. So Java 1.5 comes to the rescue with a new type of for-loop: the For-Each loop.

    Add the following code to the end of your main method:
     
       // The For-Each loop:
       System.out.println("\nNow print collections using For-Each loops:\n");
       System.out.println("First the integers...");
       String outString = "";
       for (int i : intList) {
           outString += i + " ";
       }
       System.out.println(outString + "\n");

    Now run your program. The new for loop creates the appropriate iterator object, instantiated for the desired type, behind the scenes calling hasNext() and next(). Look at this syntax, and figure out what it means and how it produces the output it does. Once you think you understand, add one more for-each loop to print out the strings in stringList.
       
  5. Save and run your project, and when it successfully prints both lists to the monitor, submit your lab.  Here is some sample output:

    init:
    deps-jar:
    Compiling 1 source file to /Users/mlsmith/Desktop/JavaApplication8/build/classes
    compile:
    run:

    Printing collections via printList method:

    1 4 9 16 25 36 49 64 81 100
    Java is an object-oriented programming language that is fun to learn

    Now print collections using For-Each loops:

    First the integers...
    1 4 9 16 25 36 49 64 81 100

    Next the Strings...
    Java is an object-oriented programming language that is fun to learn
    BUILD SUCCESSFUL (total time: 2 seconds)

Submitting your work

From a terminal window, type the following commands:

        cd
        cd cs102
        submit102 Lab3

Log out

When you are done, close NetBeans, and then locate the logout button on the menu bar. Click on the logout button (red arrow pointing through an open door).  Choose "Logout..." and then click "Yes" when prompted.  Always remember to log out when you are done using the system, to ensure that no one else uses your account.