Java Reference
In-Depth Information
With
Number
defined as the superclass for the numeric classes, we can define methods to
perform common operations for numbers. Listing 13.5 gives a program that finds the largest
number in a list of
Number
objects.
L
ISTING
13.5
LargestNumbers.java
1
import
java.util.ArrayList;
2
import
java.math.*;
3
4
public class
LargestNumbers {
5
public static void
main(String[] args) {
6 ArrayList<Number> list =
new
ArrayList<>();
7 list.add(
45
);
// Add an integer
8 list.add(
3445
.
53
);
// Add a double
9
// Add a BigInteger
10 list.add(
new
BigInteger(
"3432323234344343101"
));
11
// Add a BigDecimal
12 list.add(
new
BigDecimal(
"2.0909090989091343433344343"
));
13
14 System.out.println(
"The largest number is "
+
15 getLargestNumber(list));
16 }
17
18
create an array list
add number to list
invoke
getLargestNumber
public static
Number getLargestNumber(ArrayList<Number> list) {
19
if
(list ==
null
|| list.size() ==
0
)
20
return null
;
21
22 Number number = list.get(
0
);
23
for
(
int
i =
1
; i < list.size(); i++)
24
if
(number.doubleValue() < list.get(i).doubleValue())
25 number = list.get(i);
26
27
doubleValue
return
number;
28 }
29 }
The largest number is 3432323234344343101
The program creates an
ArrayList
of
Number
objects (line 6). It adds an
Integer
object,
a
Double
object, a
BigInteger
object, and a
BigDecimal
object to the list (lines 7-12).
Note that
45
is automatically converted into an
Integer
object and added to the list in line
7 and that
3445.53
is automatically converted into a
Double
object and added to the list in
line 8 using autoboxing.
Invoking the
getLargestNumber
method returns the largest number in the list (line 15).
The
getLargestNumber
method returns
null
if the list is
null
or the list size is
0
(lines
19-20). To find the largest number in the list, the numbers are compared by invoking their
doubleValue()
method (line 24). The
doubleValue()
method is defined in the
Number
class and implemented in the concrete subclass of
Number
. If a number is an
Integer
object, the
Integer
's
doubleValue()
is invoked. If a number is a
BigDecimal
object, the
BigDecimal
's
doubleValue()
is invoked.
If the
doubleValue()
method were not defined in the
Number
class, you will not be able
to find the largest number among different types of numbers using the
Number
class.
13.4
✓
✓
Why do the following two lines of code compile but cause a runtime error?
Check
Point
Number numberRef =
new
Integer(
0
);
Double doubleRef = (Double)numberRef;
Search WWH ::
Custom Search