I am reading the book “Core Java” by Hortsmann and Cornell (Vol.1).
In the Generics chapter, they suggest an input that is purposely wrong, in order to have a look at what the compiler says. My problem is: not only the compiler doesn’t give me the same error, but it will keep on giving me errors also when I correct the input as stated in the book. Here’s the deal:
public class PairTest1 {
public static void main(String[] args) {
double middle = ArrayAlg.getMiddle(3.14, 1729, 0);
}
}
class ArrayAlg {
public static <T> T getMiddle(T[] a) {
return a[a.length / 2];
}
}
The book says I should get the error:
found: java.lang.Number&java.lang.Comparable>, required: double.
Instead, Eclipse won’t let me run the program, saying
The method getMiddle(T[]) in the type ArrayAlg is not applicable for
the arguments (double, int, int)
The book then says
the remedy is to write all parameters as double values.
I therefore changed 1729 to 1729.1 and 0 to 0.1. Now Eclipse says:
The method getMiddle(T[]) in the type ArrayAlg is not applicable for
the arguments (double, double, double)
Mmmhh… I didn’t get what is going on. Suggestions?
Thank you & regards
EDIT: I tried to create the array double[] doubles = { 3.14, 1729.1, 0.1 }; and to give it as parameter, but now I get the error The method getMiddle(T[]) in the type ArrayAlg is not applicable for the arguments (double[])
You should change your call to
If you want to pass them the way you are doing, then you should change the declaration to
using the var-arg syntax of Java. Then you can call the method as