Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Even More About Arrays
-
To find the length of an array as an int, use arrayName.length;
-
Note, this is length as an attribute, not as a method. Thus, do not
add () after length.
-
If this sounds inconsistent, it is. For a String, we find the length
(number of characters) via the length() method. For a Vector
(which we'll discuss later in class), we use size(). Crazy,
huh? It confuses me!
-
The java.util.Arrays class contains handy methods that work on arrays.
Note, there are many variations on the parameter types of these methods.
I have listed them generically.
-
fill(array) : Fills the array with a specified value.
-
equals(array1, array2) : Returns true if the two arrays are equal.
-
binarySearch(array, key) : Searches for the specified key in the array.
-
sort(array) : Perhaps one of the most useful. Sorts an array, according
to the natural ordering of the elements.
-
Java implements multidimensional arrays by making arrays of arrays.
But you don't need to worry about the techinical details. You just
need to know that you can delcare an array like this: String
names[][] = new String [34][2];
-
Thus, the array names can hold 34 first names and 34 last names.
Example:
names[0][0] = "Conrad";
names[0][1] = "McMasters";
names[1][0] = "Lee";
names[1][1] = "Way";
-
Now, do you see where a loop can make this easy?
Example: GoBearcats
Created by: Brandan
Jones January 4, 2002