CS125 Fall 2008

Lab # 5

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

In this laboratory exercise you will implement a stand-alone class that has a static method printList and a main method. You will implement both of these methods according to the specifications given below and use generic classes from the Java Collections Framework. The generic classes are array-based and reference-based implementations of the List<E> interface, shown below.

The List<E> Interface 

The List<E> interface in the Java Collections Framework contains the operations listed below (among others). The List<E> interface is an example of a generic interface because the data type of E is not known until the class is implemented. Thus, this interface provides a template for any classes that implement it. Using generics is more convenient than using the pre-Java 1.5 technique of substituting the Object class in place of the generic place-holder E because there is no need to cast an item when accessing it or removing it from a collection. A more complete description of the List interface is given on page 276 of the text.

 

            boolean add(E obj);

           // Appends 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 

 Iterator<E> has the following method definitions (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 of generic type E in the list

 

Iterable<E> contains the following method definition:

 

         Iterator<E> iterator( );

         // Returns an Iterator over the collection

 Write a class that uses the generic List and Iterator

  1. Create a stand-alone program named Lab5.

  2. Declare a main() method so the program has a place to start execution.
     
    Inside the main method, you should declare two local variables of type List<E>, as follows:

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

    List<Integer> indicates that the type of intList is a list of Integer objects;  List<String>  indicates that stringList  is a list of String objects. The LinkedList and ArrayList classes must contain reference (object) types, not primitive types (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.
     
    Both LinkedList and ArrayList are generic classes that implement the List<E> interface, so these classes can be declared as type List<E> as shown above. The List<E> interface extends the Iterable<E> interface. Therefore, both the LinkedList and ArrayList classes provide implementations of all the methods in the List<E> and Iterable<E> interfaces. The Iterator<E> object returned from the iterator method of the ArrayList and LinkedList classes has implementations for the hasNext() and next() methods you will use in step 3.
     
    Remember to include an import statement for the package that contains List, LinkedList, and ArrayList.
     
  3. Add the following static method to class Lab5:

       /** prints elements in a collection using iterator parameter */
       public static void printList(Iterator itr) {
          String outString = ...        // initialize empty String
          while (itr.hasNext()) {
              // code using itr.next() to build outString  
          }
          System.out.println(outString);
       }

     
    The above method is incomplete. The structure for using the given iterator is provided in the code above, but you must fill in the code to initialize and construct the String containing the list elements. Your output should be formatted like the sample output shown in step 7. Be sure to import the  package that allows you to use the Iterator class.

  4. Now write the code to test the printList method. Inside the main method,
     
    1. use a for-loop to add the square of the integers from 1 to 10, inclusive, to intList,
       
    2. Declare a local array of String objects and initialize it with the following initialization list:
         
      {"Java", "is", "an", "object-oriented", "programming", "language", "that", "is", "fun", "to", "learn"}
         

      After storing these Strings in an array, you can use a for-loop to copy the elements of the array to stringList.
         
  5. Obtain an iterator from both of these lists, using syntax like that shown in the line below, 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 the intList variable you defined in setp 2:
     
        Iterator<Integer> intIterator = intList.iterator();
        
    After you get the printList method working, run your program for your professor or Sonia (our splendiferous coach) before continuing.
     
  6. In this step, you will produce the same output as you did with the printList method described in step 3, but this time you will use an Iterator implicitly, not explicitly, by using a for-each loop.
     
    The for-each loop (also known as the enhanced for-loop) makes using iterators a bit less tedious.

    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 for loop creates the appropriate iterator object, implicitly instantiated for the desired type, calling hasNext() and next() behind the scenes. Look at this syntax, and figure out what it means and how it produces the output it does. Once you think you understand, add another for-each loop to print out the strings in stringList.
       
  7. Save and run your project, and when it successfully prints both lists to the monitor, submit your lab.  
     
    Be sure your output matches that shown below:

     
    Printing collections via printList method:

       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
      

    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

Submitting your work

Save your work in a folder called Lab5.  From a terminal window, type the following commands:

        cd
        cd cs125
        submit125 Lab5

Log out

When you are done, log out. 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.