Java Reference
In-Depth Information
1
import java.math.BigInteger;
2
3
class FindMaxDemo
4
{
5
/**
6
* Return max item in a.
7
* Precondition: a.length > 0
8
*/
9
public static Comparable findMax( Comparable [ ] a )
10
{
11
int maxIndex = 0;
12
13
for( int i = 1; i < a.length; i++ )
14
if( a[ i ].compareTo( a[ maxIndex ] ) > 0 )
15
maxIndex = i;
16
17
return a[ maxIndex ];
18
}
19
20
/**
21
* Test findMax on BigInteger and String objects.
22
*/
23
public static void main( String [ ] args )
24
{
25
BigInteger [ ] bi1 = { new BigInteger( "8764" ),
26
new BigInteger( "29345" ),
27
new BigInteger( "1818" ) };
28
29
String [ ] st1 = { "Joe", "Bob", "Bill", "Zeke" };
30
31
System.out.println( findMax( bi1 ) );
32
System.out.println( findMax( st1 ) );
33
}
34
}
figure 4.29
A generic
findMax
routine, with demo
using shapes and
strings (pre-Java 5)
Fourth, it is not required that the interface be a standard library interface.
Finally, this solution does not always work, because it might be impossi-
ble to declare that a class implements a needed interface. For instance, the
class might be a library class, while the interface is a user-defined interface.
And if the class is final, we can't even create a new class. Section 4.8 offers
another solution for this problem, which is the
function object
. The function
object uses interfaces also, and is perhaps one of the central themes encoun-
tered in the Java library.
Search WWH ::
Custom Search