Java Reference
In-Depth Information
Java treats a variable-length parameter as an array. You can pass an array or a variable
number of arguments to a variable-length parameter. When invoking a method with a vari-
able number of arguments, Java creates an array and passes the arguments to it. Listing 7.5
contains a method that prints the maximum value in a list of an unspecified number of values.
L ISTING 7.5
VarArgsDemo.java
1 public class VarArgsDemo {
2
public static void main(String[] args) {
3
printMax( 34 , 3 , 3 , 2 , 56 . 5 );
pass variable-length arg list
pass an array arg
4
printMax( new double []{ 1 , 2 , 3 });
5 }
6
7 public static void printMax( double ... numbers) {
8 if (numbers.length == 0 ) {
9 System.out.println( "No argument passed" );
10
a variable-length arg
parameter
return ;
11 }
12
13
double result = numbers[ 0 ];
14
15 for ( int i = 1 ; i < numbers.length; i++)
16 if (numbers[i] > result)
17 result = numbers[i];
18
19 System.out.println( "The max value is " + result);
20 }
21 }
Line 3 invokes the printMax method with a variable-length argument list passed to the array
numbers . If no arguments are passed, the length of the array is 0 (line 8).
Line 4 invokes the printMax method with an array.
7.19
What is wrong in the following method header?
Check
Point
public static void print(String... strings, double ... numbers)
public static void print( double ... numbers, String name)
public static double ... print( double d1, double d2)
7.20
Can you invoke the printMax method in Listing 7.5 using the following statements?
printMax( 1 , 2 , 2 , 1 , 4 );
printMax( new double []{ 1 , 2 , 3 });
printMax( new int []{ 1 , 2 , 3 });
7.10 Searching Arrays
If an array is sorted, binary search is more efficient than linear search for finding an
element in the array.
Key
Point
Searching is the process of looking for a specific element in an array—for example, discov-
ering whether a certain score is included in a list of scores. Searching is a common task in
computer programming. Many algorithms and data structures are devoted to searching. This
section discusses two commonly used approaches, linear search and binary search .
linear search
binary search
7.10.1 The Linear Search Approach
The linear search approach compares the key element key sequentially with each element in
the array. It continues to do so until the key matches an element in the array or the array is
exhausted without a match being found. If a match is made, the linear search returns the index
 
 
 
Search WWH ::




Custom Search