泛型方法调用报错:参数匹配却无法调用minIndex()?
泛型排序方法调用编译错误解决
问题描述
编写了一个静态泛型方法sort(),基于最小索引对数组排序(排序逻辑依赖对象类重写的compareTo()方法),调用另一个静态泛型方法minIndex()获取数组最小索引时,出现编译错误:
The method minIndex(E[], int) in the type Lab11_2 is not applicable for the arguments (E[], int)
现有代码
sort()方法
// Sorts any array by the order of the minimum index. public static <E> E[] sort(E[] arr){ int minInd; E tempObj; for(int i = 0; i < arr.length; i++){ minInd = minIndex(arr, i); // Get the minimum index of the array. // Swap the object with the minimum index with the object at index 'i'. tempObj = arr[minInd]; arr[minInd] = arr[i]; arr[i] = tempObj; } return arr; }
minIndex()方法
// Returns the minimum index of an array. public static <E extends Comparable<E>> int minIndex(E[] arr, int start){ int ind = start; for(int k = start + 1; k < arr.length; k++){ if(arr[k].compareTo(arr[ind]) < 0){ ind = k; } } return ind; }
错误原因与解决方案
错误原因
minIndex()的泛型参数E有明确约束:E extends Comparable<E>,要求传入的数组元素必须实现Comparable接口(才能调用compareTo()方法)。但sort()的泛型参数E没有任何约束,编译器无法保证sort()传入的E[]元素符合minIndex()的要求,因此触发编译错误。
解决方案
修改sort()的泛型声明,给E加上相同的Comparable约束,确保传入的数组元素类型满足minIndex()的参数要求:
// Sorts any array by the order of the minimum index. public static <E extends Comparable<E>> E[] sort(E[] arr){ int minInd; E tempObj; for(int i = 0; i < arr.length; i++){ minInd = minIndex(arr, i); // Get the minimum index of the array. // Swap the object with the minimum index with the object at index 'i'. tempObj = arr[minInd]; arr[minInd] = arr[i]; arr[i] = tempObj; } return arr; }
修改后,两个方法的泛型参数约束一致,编译器可确认参数类型合法,编译错误即可解决。
内容的提问来源于stack exchange,提问作者Ethan Waldeck
相关产品推荐
相关产品推荐

