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");
Compilation "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" with 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 skipped adding a 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 explain why compilation does not crash in the second case? I expected the compiler to complain about T extends Comparable, does V extend T in the second instance?
What's happening?