Radford University ITEC

ITEC120-ibarland (incl. office hrs)infolectureslabshws

lecture 13: arrays

We first talked about common hw05 problems.

We have seen lists, which are an extremely handy class, for keeping around a bunch of objects. (Note that even though the class is named ArrayList<>, the “array” is misleading—it's just a list.)

Today we discuss another type of container object: arrays. (Powerpoint slides for Chpt. 7 are available on the class's WebCT page.)

Arrays vs Lists

In practice, lists prove much more flexible than arrays: it's much more common to have data of the form “0 or more data” than “exactly 100 data”. ArrayList<Type> is almost always what you want, despite its slightly verbose name.

ITEC120-ibarland (incl. office hrs)infolectureslabshws


Nov.14 (Tue)

Iterating over an array

We have already seen and written loops which can process each element of a list—either via a for-each loop (which doesn't give us the index), or by having a loop-variable range over the valid indices and call get manually.

Both these approaches also work with arrays:

import java.util.ArrayList;
import java.util.Random;
final  randy = new java.util.Random();
final int MAX_RAND = 5000;

final int N = 100;  // The number of items in the array or list.

int[] myArray = new int[N];
ArrayList<Integer> myList = new ArrayList<Integer>(N);

for (int i = 0; i < N; ++i ) {
  // Fill up myArray and myList with random values.
  myArray[i] = randy.nextInt( MAX_RAND );
  myList.set( i, randy.nextInt( MAX_RAND ) );
  /* Fragile: i is always the maximum legal value to set, on each pass.
   * Also note: While the array could be initialized from N-1 down to 0,
   * doing so with the list (always adding at index 0) would be notably
   * inefficient, due to the constant shifting-over being done every time.
   */
  }

long totalSoFarArray = 0; // Track the running total.
long totalSoFarList  = 0; 

for ( int datum : myArray ) {
  totalSoFarArray += datum;
  }

for ( int datum : myList ) {  // Rely on auto-unboxing, from Integer to int.
  totalSoFarList += datum;
  }


// Now compute the averages, in BlueJ's code pad:
totalSoFarList / myList.size()
totalSoFarArray / myArray.length


ITEC120-ibarland (incl. office hrs)infolectureslabshws


©2006, Ian Barland, Radford University
Last modified 2006.Nov.13 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme