ITEC120-ibarland (incl. office hrs)—info—lectures—labs—hws
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
- Arrays hold a fixed number of items,
whereas lists can hold any number of items.
- Arrays can hold primitive values, whereas lists only contain
actual objects. (This drawback is ameliorated by the wrapper classes
and auto-boxing, as we saw.)
-
To access elements of an array by index, use […];
for lists, use the get(…) method.
That is,
myArray[3] vs. myList.get(3).
While the array syntax is shorter, it's a bit confusing to introduce a
whole new type of punctuation which is really just a method-call in disguise.
-
Both arrays and lists let you
replace the item at a certain index:
myArray[3] = newVal;
(see powerpoint/book),
vs.
myList.set( 3, newVal );.
Thus the square-bracket notation can mean either get
or set, depending on context.
(Again, this is a trade-off between shorter notation,
and having brand-new notation which we didn't have to worry about before.)
-
In an array, there is no way to automatically add or remove a new element
in the middle, and have all the other elements slide over to
fill/create the gap.
Lists have versions of remove and add which
do this, taking an index as (one of) their arguments.
-
When calling a constructor for type int[],
you must provide one argument: the size of the array (which is
then forever fixed).
But instead of writing new int[](100),
you write new int[100].
In fact, this is the first time when the declared-type and
the new don't quite match up:
int[] data = new int[100];.
- To get the size of a list, you use the method size().
To get the size of an array, you use the field length:
That is, myList.size() vs. myArray.length.
(Note the lack of parentheses, since we're accessing a field directly,
not calling a getter-method).
-
In both arrays and lists with N elements,
valid indices are in the range [0,N) (that is,
N-1 is the largest valid index).
Far and away the most common runtime beginner-mistake with arrays and lists is
“index out of bounds exception”, from trying to use
N (or occasionally -1) as an index.
-
The built-in toString for arrays is pathetic.
Instead use
the static method
static java.util.Arrays.toString(type[]).
Note the ‘s’ on the
end of ‘Arrays’.
(The class java.util.Arrays is a class of static methods,
whose purpose is to fill in methods missing from the first version of Java.
Since you can't add on to array classes, in Java, this class
was kludged on.)
Don't get confused by documentation for similarly-named classes
java.lang.reflect.Array or java.sql.Array, yikes!)
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)—info—lectures—labs—hws
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)—info—lectures—labs—hws