CS 162 Lecture-Module #05:
Collections (Chapter 4)

|ArrayList|

* flexible collections of objects
* unlimited and unknown size
* iPod playlist as an example

technical specifications:

AT TOP OF SOURCE CODE:
import java.util.ArrayList;
OR
import java.util.*;

declaration:
ArrayList<Song> playList;               // declaration

creation:
playList = new ArrayList<Song>();       // creation

these are like what done before
but type instead of e.g.  Circle  or  SimpleDate  it's  ArrayList<Song>
(official Java lingo "generic type"; I say "parameterized type")

use:
*  void playList.add(Object)       // addition at end of list
*  int playList.size()             // returns # of things currently in list
*  Object playList.get(int index)  // selection: returns object at index
*  Object playList.remove(int index)
* indexing starts at 


e.g.   pages 108-109
    ArrayList<Lot> lots;                // declaration

    lots = new ArrayList<Lot>();        // creation

    Lot newLot = new Lot(nextLotNumber, description);
    lots.add(newLot);                   // addition
    
    Lot selectedLot = lots.get(lotNumber - 1);  // selection
e.g. list of names of people in class:
    // declaration
    ArrayList<String> students;

    // creation:
    students = new ArrayList<String>();

    // addition:
    students.add("Lee Shepich");
    students.add("Jim Hanley");
    students.add("Nathan Biller");

    System.out.println( students.size() );      // outputs 3

    students.add("Chadwick Medendorp");

    System.out.println( students.get(2) );      // outputs "Nathan Biller"

    students.remove(1);                         // removes "Jim Hanley"

    System.out.println( students.get(1) );      // outputs "Nathan Biller"

Iterative Processing

to process all elements of list, use 'for-each' 'loop'
    for ( String s : students ) {
        // whatever you want to do to element s from list e.g.
        System.out.println( s );
        System.out.println("the length of this name is " + s.length() );
        }

    for ( Song s : playList ) {
        // whatever processing ...
        }

    // pages 108-109:
    for ( Lot lot : lots ) {
        System.out.println( lot.toString() );
        }
alternatively, use  loop
int x = 0;
while ( x < students.size() ) {
    String s = students.get(x);
    System.out.println( s );
    System.out.println("the length of this name is " + s.length() );

    x++;
    }
Exercise 4.19 (Challenge task: Write a method  isPrime(int n)  that returns true
if the parameter n is a prime number, and false if it is not.
... a while loop that checks whether n is divisible by ?all? numbers
between 2 and n-1 ... the modulo operator (%) to check whether the
integer division leaves a remainder of 0.
public class util {

alternatively:




Notebook lab provides exploration of this material:
the textbook actually provides essentially all of the code employing  ArrayList  and  while
which you then type or invoke;
thus you see how this stuff functions


Using Iterator

another way to access elements of list while processing them
Iterator<String> sit = students.iterator();
while ( sit.hasNext() ) {
    String s = sit.next();
    System.out.println( s );
    System.out.println("the length of this name is " + s.length() );
    if ( s.equals("Jacob") ) {
        sit.remove();
    }
}

arrays

(Section 4.12: "Fixed-size collections")
more primitive collections than  ArrayLists
similar functionalities; the parallel usages of the two are as follows:
    ArrayList                           array
    --------                            -----
    ArrayList<String> notes;            String[] notes;
    notes = new ArrayList<String>();    notes = new String[10];
    notes.add(note);                    notes[3] = note;
    note = notes.get(3);                note = notes[3];
use for-each the same with both  ArrayList  and array
significant difference:  ArrayList.add(...)  makes  ArrayList  grow as necessary; with array one must specify length at outset
and can use only appropriate entries


by the way to check whether an element of list is equal to "Jacob":
    int number_of_Jacobs = 0;
    for ( String s : students ) {
        // whatever you want to do to element s from list e.g.
        System.out.println( s );
        System.out.println("the length of this name is " + s.length() );

        // check whether |s| is equal to "Jacob":
            // 'equals' ha-ha?
        if ( s.equals("Jacob") ) {      // versus   if ( s == "Jacob" ) ...
            number_of_Jacobs++;
            }
        }
    System.out.println("number of Jacobs: " + number_of_Jacobs);
to stop processing at "Riddle":
    boolean found_Riddle = false;
    for ( String s : students ) {
        // whatever you want to do to element s from list e.g.
        System.out.println( s );
        System.out.println("the length of this name is " + s.length() );

        // check whether |s| is equal to "Riddle":
            // 'equals' ha-ha?
        if ( s.equals("Riddle") ) {     
            found_Riddle = true;
            break;
            }
        }
    System.out.println("was there a Riddle? " + found_Riddle);

initialization of array's elements

background (review):
int  i;
.
.
.
i = 35;

OR together:
int  i = 35;
double z = 0.618;

with arrays, get default initial value for each element:


or you can specify (other) initial values you might want
    at declaration as w/basic variables
as follows:
element_type[] array_name =
    { init_elt0init_elt1init_elt2, ... };

e.g.  
int[] data = { 93,      
                26,     
                41,     
                85,     
                74      
                };
length is num. of initial values you provide

in this case don't need to do array_name = new element_type[num._of_elements];
    e.g. not data = new int[5];

rem. only at declaration
e.g. if try:
int [] data;
...
data = { 93, 26, 41, 85, 74 };    




old  for
starts like  for  presented above which is called 'foreach' or 'enhanced for'
provides no more than  while  --- require 4 lines of code to do what 'foreach'
does in 1 line

puts various iteration-controlling elements of  while  together in one place
        initialization: int x = 0
        condition: x < students.size()
        incrementation: x++
the place is all inside parentheses following the word  for:
with semi-colons separating pieces
e.g.:
// same functionality as |while| earlier
for ( int x = 0; x < students.size(); x++ ) {
    String s = students.get(x);
    System.out.println( s );
    System.out.println("the length of this name is " + s.length() );
    }

// textbook page 121:
for ( int hour = 0; hour < hourCounts.length; hour++ )
    ...

for ( int count = 0; count < LIMIT; count++ )
    ...
similar to  while
but again all pieces together
for this reason, this  for  may be preferable to  while

try exercises on iteration using  for
1. write method returning sum of values of double array parameter
using this  for:

or (better) using 'foreach':


2. how about writing a method to obtain average of values in array?


3. write a method to return location of target value in array:


4. write a method to return location of maximum value in array:


(Copyright © 2009 by Hugh McGuire   — for thoughts about this, see   http://www.cis.gvsu.edu/~mcguire/teaching/copyright_thoughts.html .)