Generic Wildcard Arguments

To create a generic method, you use the wildcard argument. The wildcard argument is specified by the ?, and it represents an unknown type.

``````
class Calculator<T extends Number> {
T[] nums;
Calculator(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for (int i = 0; i < nums.length; i++){
sum += nums[i].doubleValue();
}
return sum / nums.length;
}
}
public class Main {
boolean sameAvg(Calculator<?> ob) {
if (1.2 == ob.average())
return true;
return false;
}

public static void main(String args[]) {
}
}

``````

Calculator<?> matches any Stats object, allowing any two Stats objects to have their averages compared.

The following program demonstrates this:

``````
class Calculator<T extends Number> {
T[] nums;
Calculator(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for (int i = 0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}
boolean sameAvg(Calculator<?> ob) {
if (average() == ob.average())
return true;
return false;
}
}
public class Main {
public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
Calculator<Integer> iob = new Calculator<Integer>(inums);

Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Calculator<Double> dob = new Calculator<Double>(dnums);

if (iob.sameAvg(dob))
System.out.println("are the same.");
else
System.out.println("differ.");
}
}

``````
Home
Java Book
Language Basics

Generics: