| | | Getting the length of an array |
Getting the length of an array
A detail about Java arrays: If you have created an array (i.e., you
have actually executed something like myArray = new
SomeType[someSize] you can ask the array for its length. You can get
the length by writing myArray.length. Notice there are no
parentheses after length. You are actually accessing (gasp!) a
public instance variable. This is one of the few times that the Java
libraries allow the user to access a public instance variable. I
personally find it very confusing to have this be an instance variable
rather than a method, since other very similar classes (like
Vector and String) provide a method rather than an
instance variable which return the size of the structure.
You might ask why you might ever need this information. The main
reason it might be necessary is if you get an array passed as a
parameter. If it comes as a parameter, you may not have any idea how
large it is. Here is a method which takes as a parameter an array of
double's and returns the largest element in the array.
// return largest value in elt array. Require the array parameter to have
// length at least 1 (so there is an element there)
public double largest(double[] elt)
{
double largest = elt[0];
for (int index=1; index < elt.length; index++)
{
if (elt[index] > largest)
largest = elt[index];
}
return largest;
}
Of course this code only works if all the slots in the array hold useful
values. If only some of the array elements hold useful information, then
we can ensure we only search those elements by passing the useful size as a
parameter:
// return largest value in first size elements of elt array. Require that
// size >= 1 and that the array parameter have length at least size.
public double largest(double[] elt, int size)
{
double largest = elt[0];
for (int index=1; index < size; index++)
{
if (elt[index] > largest)
largest = elt[index];
}
return largest;
}
| | | Getting the length of an array |