Java Reference
In-Depth Information
1
// Fig. 20.14: WildcardTest.java
2
// Wildcard test program.
3
import java.util.ArrayList;
4
5
public class WildcardTest
6
{
7
public static void main(String[] args)
8
{
9
// create, initialize and output ArrayList of Integers, then
10
// display total of the elements
11
Integer[] integers = { 1 , 2 , 3 , 4 , 5 };
12
ArrayList<Integer> integerList = new ArrayList<>();
13
14
// insert elements in integerList
15
for (Integer element : integers)
16
integerList.add(element);
17
18
System.out.printf( "integerList contains: %s%n" , integerList);
19
System.out.printf( "Total of the elements in integerList: %.0f%n%n" ,
20
sum(integerList)
);
21
22
// create, initialize and output ArrayList of Doubles, then
23
// display total of the elements
24
Double[] doubles = { 1.1 , 3.3 , 5.5 };
25
ArrayList<Double> doubleList = new ArrayList<>();
26
27
// insert elements in doubleList
28
for (Double element : doubles)
29
doubleList.add(element);
30
31
System.out.printf( "doubleList contains: %s%n" , doubleList);
32
System.out.printf( "Total of the elements in doubleList: %.1f%n%n" ,
33
sum(doubleList)
);
34
35
// create, initialize and output ArrayList of Numbers containing
36
// both Integers and Doubles, then display total of the elements
37
Number[] numbers = { 1 , 2.4 , 3 , 4.1 }; // Integers and Doubles
38
ArrayList<Number> numberList = new ArrayList<>();
39
40
// insert elements in numberList
41
for (Number element : numbers)
42
numberList.add(element);
43
44
System.out.printf( "numberList contains: %s%n" , numberList);
45
System.out.printf( "Total of the elements in numberList: %.1f%n" ,
46
sum(numberList)
);
47
} // end main
48
49
// total the elements; using a wildcard in the ArrayList parameter
50
public static double sum(
ArrayList<? extends Number>
list)
51
{
52
double total = 0 ; // initialize total
53
Fig. 20.14 | Wildcard test program. (Part 1 of 2.)
Search WWH ::




Custom Search