I have this piece of code from "Java - A beginner's Guide - Schildt', Chapter 13:
package com.chapter.thirteen;
public class GenericMethodDemo {
static <T extends Comparable<T>, V extends T> boolean arraysEqual(T[] x, V[] y){
if(x.length != y.length) return false;
for(int i = 0; i < x.length; i++)
if(!x[i].equals(y[i])) return false;
return true;
}
public static void main(String args[]){
Integer [] nums = { 1, 3, 3, 4, 6 };
Integer [] nums2 = { 1, 3, 3, 4, 6 };
Integer [] nums3 = { 1, 3, 3, 4, 6 };
Integer [] nums4 = { 1, 3, 3, 4, 6, 7};
Double [] dVals = {1.1, 2.2, 3.3, 4.4};
if(arraysEqual(nums, nums))
System.out.println("nums equal nums");
if(arraysEqual(nums, nums2))
System.out.println("nums equal nums2");
if(arraysEqual(nums, nums2))
System.out.println("nums equal nums2");
if(arraysEqual(nums, nums3))
System.out.println("nums equal nums3");
if(arraysEqual(nums, nums4))
System.out.println("nums equal nums4");
//Edit:Removed the comments from the below two lines.
if(arraysEqual(nums, dVals))
System.out.println("Nums equal dVals");
}
}
The compilation fails with the message -
"Error:(39, 12) java: method arraysEqual in class com.chapter.thirteen.GenericMethodDemo cannot be applied to given types; required: T[],V[] found: java.lang.Integer[],java.lang.Double[] reason: inference variable T has incompatible bounds equality constraints: java.lang.Integer lower bounds: V,java.lang.Double,java.lang.Integer"
,
which is expected.
However, when I missed adding the parameter to Comparable (as shown in the code below), the code compiles and produces the correct result.
package com.chapter.thirteen;
public class GenericMethodDemo {
static <T extends Comparable, V extends T> boolean arraysEqual(T[] x, V[] y){
if(x.length != y.length) return false;
for(int i = 0; i < x.length; i++)
if(!x[i].equals(y[i])) return false;
return true;
}
public static void main(String args[]){
Integer [] nums = { 1, 3, 3, 4, 6 };
Integer [] nums2 = { 1, 3, 3, 4, 6 };
Integer [] nums3 = { 1, 3, 3, 4, 6 };
Integer [] nums4 = { 1, 3, 3, 4, 6, 7};
Double [] dVals = {1.1, 2.2, 3.3, 4.4};
if(arraysEqual(nums, nums))
System.out.println("nums equal nums");
if(arraysEqual(nums, nums2))
System.out.println("nums equal nums2");
if(arraysEqual(nums, nums2))
System.out.println("nums equal nums2");
if(arraysEqual(nums, nums3))
System.out.println("nums equal nums3");
if(arraysEqual(nums, nums4))
System.out.println("nums equal nums4");
if(arraysEqual(nums, dVals))
System.out.println("Nums equal dVals");
}
}
Can someone please explain why the compilation does not fail in the second instance? I had expected the compiler to complain about T extends Comparable, V extends T in the second instance?
What's going on?