Java Reference
In-Depth Information
inserting the numbers in the collection. Because generic classes can be used only with class
or interface types, the numbers would be autoboxed as objects of the type-wrapper classes.
For example, any int value would be autoboxed as an Integer object, and any double val-
ue would be autoboxed as a Double object. We'd like to be able to total all the numbers in
the ArrayList regardless of their type. For this reason, we'll declare the ArrayList with
the type argument Number , which is the superclass of both Integer and Double . In addi-
tion, method sum will receive a parameter of type ArrayList<Number> and total its ele-
ments. Figure 20.13 demonstrates totaling the elements of an ArrayList of Number s.
1
// Fig. 20.13: TotalNumbers.java
2
// Totaling the numbers in an ArrayList<Number>.
3
import java.util.ArrayList;
4
5
public class TotalNumbers
6
{
7
public static void main(String[] args)
8
{
9
// create, initialize and output ArrayList of Numbers containing
10
// both Integers and Doubles, then display total of the elements
11
Number[] numbers = { 1 , 2.4 , 3 , 4.1 }; // Integers and Doubles
ArrayList<Number> numberList = new ArrayList<>();
12
13
14
for (Number element : numbers)
15
numberList.add(element); // place each number in numberList
16
17
System.out.printf( "numberList contains: %s%n" ,
numberList
);
18
System.out.printf( "Total of the elements in numberList: %.1f%n" ,
19
sum(numberList)
);
20
}
21
22
// calculate total of ArrayList elements
23
public static double sum(
ArrayList<Number>
list)
24
{
25
double total = 0 ; // initialize total
26
27
// calculate sum
28
for (Number element : list)
total += element.doubleValue();
29
30
31
return total;
32
}
33
} // end class TotalNumbers
numberList contains: [1, 2.4, 3, 4.1]
Total of the elements in numberList: 10.5
Fig. 20.13 | Totaling the numbers in an ArrayList<Number> .
Line 11 declares and initializes an array of Number s. Because the initializers are prim-
itive values, Java autoboxes each primitive value as an object of its corresponding wrapper
type. The int values 1 and 3 are autoboxed as Integer objects, and the double values 2.4
 
Search WWH ::




Custom Search