Java Reference
In-Depth Information
{
int
maxIndex = 0;
//Assume first element is the largest
for
(
int
index = 1; index < numOfElements; index++)
if
(list[maxIndex] < list[index])
maxIndex = index;
return
maxIndex;
}
//Method to copy some or all the elements of one array
//into another array. Starting at the position specified
//by src, the elements of list1 are copied into list2
//starting at the position specified by tar. The parameter
//numOfElements specifies the number of elements of list1 to
//be copied into list2. Starting at the position specified
//by tar, list2 must have enough components to copy the
//elements of list1. The following call copies all the
//elements of list1 into the corresponding positions in
//list2: copyArray(list1, 0, list2, 0, numOfElements);.
public static void
copyArray(
int
[] list1,
int
src,
int
[] list2,
int
tar,
int
numOfElements)
{
for
(
int
index = src; index < src + numOfElements; index++)
{
list2[index] = list1[tar];
tar++;
}
9
}
}
Because the methods of the
class
OneDimArrayMethods
are
public
and
static
,they
can be called by using the name of the class and the dot operator. For example, if
myList
is
an array of 10 elements of type
int
, the following statement outputs the elements of
myList
:
OneDimArrayMethods.printArray(myList, myList.length);
Just as arrays can be passed as parameters to methods, individual elements of the array
can also be passed as parameters to methods. For example, suppose that you have the
following statement:
int
[] list = {2, 3, 5};
and the method:
public static int
sumNum(
int
firstNum,
int
secondNum)
{
return
firstNum + secondNum;
}
The following statement outputs the sum of the first two elements of the array
list
:
System.out.println("Sum = " + sumNum(list[0], list[1]));
Search WWH ::
Custom Search