Java Reference
In-Depth Information
boolean
areEqualArrays(
int
[] firstArray,
int
[] secondArray)
{
if
(firstArray.length != secondArray.length)
return false
;
for
(
int
index = 0; index < firstArray.length; index++)
if
(firstArray[index] != secondArray[index])
//the
//corresponding elements
//are different
return false
;
return true
;
}
Now consider the following statement:
if
(areEqualArrays(listA, listB))
...
The expression
areEqualArrays(listA, listB)
evaluates to
true
if the arrays
listA
and
listB
contain the same elements;
false
otherwise.
Just like other objects, arrays can be passed as parameters to methods. The following
method takes as an argument any
int
array and outputs the data stored in each element:
public static void
printArray(
int
[] list)
{
9
for
(
int
index = 0; index < list.length; index++)
System.out.print(list[index] + " ");
}
Methods such as the preceding one process the data of an entire array. Sometimes the
number of elements in the array might be less than the length of the array. For example,
the number of elements in an array storing student data might increase or decrease as
students drop or add courses. In situations like this, we only want to process the elements
of the array that hold actual data. To write methods to process such arrays, in addition to
declaring an array as a formal parameter, we declare another formal parameter specifying
the number of valid elements in the array, as in the following method:
public static void
printArray(
int
[] list,
int
numOfElements)
{
for
(
int
index = 0; index < numOfElements; index++)
System.out.print(list[index] + " ");
}
The first parameter of the method
printArray
is an
int
array of any size. When the
method
printArray
is called, the number of valid elements in the actual array is passed
as the second parameter of the method
printArray
.
Search WWH ::
Custom Search