RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoarchiveexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect11b
for-each
looping over a list

review

Declare a list of Doubles; add three numbers to it; retrieve the last number in the list; check whether Math.PI is in the list.

for-each loops

Yestersday's lab included the following snippet of code. Let's review it:

  /** Return the sum of the age of each dogs in a given list.
    * @param someDogs a list of exactly 4 dogs.
    * @return the sum of the age of each dog in someDogs.
    */
  int totalAge( java.util.LinkedList<Dog> someDogs ) {
    int totalSoFar = 0;
    Dog d;   // Over time, this variable will refer to *each* dog in the list(!)

    d = someDogs.get(0);      // d now refers to the dog at index 0.
    totalSoFar = totalSoFar + d.getAge();   /* totalSoFar now contains dog0's age. */

    d = someDogs.get(1);     // d now refers to the dog at index 1.
    totalSoFar = totalSoFar + 0;  /* MODIFY THIS LINE, so that totalSoFar now 
                                    contains dog0's age *plus* dog1's age. */

    /*  ADD TWO MORE LINES, 
     *  so that totalSoFar contains dog0's age plus dog1's age plus dog2's age. 
     *	 You are encouraged to cut-and-paste.  (We'll see a better way tomorrow.)
     */

    /*  ADD TWO MORE LINES, 
     *  so that totalSoFar contains each dog's age, all added together.
     *	 You are encoruaged to cut-and-paste.  (We'll see a better way tomorrow.)
     */


    return totalSoFar;
    }

Java provides a new type of statement, the “for-each loop”; it lets us process each element of a list, no matter how long this list is!

  /** Return the sum of the age of each dogs in a given list.
    * @param someDogs a list of any number of Dogs.
    * @return the sum of the age of each dog in someDogs.
    */
  int totalAge( java.util.LinkedList<Dog> someDogs ) {
    int totalSoFar = 0;

    for (Dog d : someDogs) {
      totalSoFar = totalSoFar + d.getAge();   /* totalSoFar now contains dog0's age. */
    }

    return totalSoFar;
    }

Similarly, we can process each Double in a list:

for ( Double d : dubs ) {  // "for each d in dubs, ..."
  System.out.println( "Currently looking at: " + d.toString() );
  }

Now, we already know that printing to the console is something which we can't build on with other methods, since it doesn't actually return any answer. So we can also use loops to actually compute something:

/* Add up elements of a list, with a for-each loop. */
double totalSoFar = 0.0;   // The running total -- an "accumulator" variable.
for ( Double d : dubs ) {  // "for each d in dubs, ..."
  totalSoFar = totalSoFar + d.doubleValue();
  }
// For-each is only appropriate when we want to handle every element exactly the same.
// To-do:
// - write a function average, which computes 
//   the average of a (non-empty!) list of numbers.
// - Augment the above code so you also accumulate the sum-of-squares
//    (or, the absolute values)
// - Augment the above code so you also accumulate a String, with each
//    number separated by a space, with angle-brackets on each side:
//      "< 5.4 -1.2 4.2 0.0 5.4 >"

Lists aren't at all specific to Doubles; they can hold any sort of object at all. Note that technically, the list holds a reference to objects. Let's draw pictures on the board:

// ======================================

Dog d1 = new Dog( "lassie", 15 )
Dog d2 = new Dog( "fido", 3 )
Dog d3 = new Dog( "phydeaux", 5 )

java.util.LinkedList<Dog> pound = new java.util.LinkedList<Dog>();

pound.add( d1 )
pound.add( d2 )
pound.add( d3 )
pound.toString()
pound.contains( d1 )
pound.contains( new Dog( "fido", 3 ) )   /* .equals, or == ?  See docs. */
pound.contains( "fido" )
pound.remove( new Dog( "fido", 3 ) )     /* .equals, or == ?  See docs. */
pound.toString()
pound.remove( d1 )
pound.toString()

a Blah is not a List-of-Blah

A number is not a list of numbers; a Dog is not a LinkedList<Dog>. Think of the list as a bag. The bag might even be empty. It is a common confusion for people to declare a field to be (say) a Treasure, when really what they want to keep track of is a LinkedList<Treasure>. Or, to ask a LinkedList<Dog> to speak(), even though that's a behavior of things in the bag, not a behavior of the bag itself. (Use a for-each loop to work with each object inside the bag.)

a bag of items

Which of the following method calls make sense?

  1. pound.getSound()
  2. d1.get(1)
  3. pound.get(1)
  4. d1.get(1)
  5. Dog d = pound.get(1) followed by d.getSound()
  6. (pound.get(1)).getSound()

Looping over lists of objects

to do:

Things to ask yourself, when writing a loop:

homeinfoarchiveexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2008, Ian Barland, Radford University
Last modified 2008.Apr.02 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme