|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
Processing a list using while and get()
For example:
Suppose doggies is a list of Dog.
// A for-each loop to add all the ages of every Dog in doggies. int agesSoFar = 0; for ( Dog d : doggies ) { agesSoFar = agesSoFar +1 d.getAge(); } |
But it turns out, before Java 1.5, the Java language had while loops, but no for-each loop! How on earth did programmers add up the ages in a list-of-Dogs? Well, a while loop can suffice, but we need to get d to refer to a different Dog each time through the loop?
// A for-each loop to add all the ages of every Dog in doggies. int agesSoFar = 0; Dog d; while ( ) { agesSoFar = agesSoFar + d.getAge(); } |
// A while-loop to add all the ages of every Dog in doggies. int agesSoFar = 0; int nextDogIndex = 0; Dog d; while ( nextDogIndex < doggies.size() ) { d = doggies.get( nextDogIndex ); agesSoFar = agesSoFar + d.getAge(); nextDogIndex = nextDogIndex +1; } |
We saw earlier that we could use for-each loops to search for an element of a list; in fact we saw multiple versions. Here's a version which looks for a happy dog in a list:
boolean foundSoFar = false; for ( Dog d : aDogList ) { foundSoFar = foundSoFar || /* code for: d is a happy dog */; } // Here,foundSoFar is true iff aDogList contains a dog we're looking for. |
A while loops is more appropriate, since we didn't want to process every single element of the list identically. We can avoid using return as part of our loop-control logic.
1We can abbreviate agesSoFar = agesSoFar + d.getAge(); as agesSoFar += d.getAge();. We don't stress “+=” because while it is more descriptive/readable once you're used to reading the shorthand, it is also new bit of syntax (overhead to learn), and it's not that much more concise. Also, be careful not to write something like “x =+ 7; //BAD CODE; that's the same as “x = +7”!” ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Jan.24 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |