TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
下面讨论的是数组的排序和搜索功能,而一个通用方法则是实现Comparable接口的方法,这个方法需要通过java泛型来实现。
下面便逐步讲解为何,以及如何通过Java泛型实现此类的通用方法。
如何在java类中实现一些通用方法, 特别是一些静态的工具方法?
比如,数组Arrays的sort、search等?
1. 整数数组的顺序搜索
- [/code]
-
- [b]public[/b] [b]static[/b] [b]int[/b] seqSearch([b]int[/b][] arr, [b]int[/b] first, [b]int[/b] last, [b]int[/b] target) {
- [b]for[/b] ([b]int[/b] i = first; i < last; i++)
- [b]if[/b] (arr[i] == target)
- [b]return[/b] i;
-
- [b]return[/b] -1;
- }
-
-
- 1.1对上面的方法进行抽象,最先让我们想到就是,使用java的Object的引用,来实现通用方法
- [code]
复制代码
public static int seqSearch(Object[] arr, int first, int last, Object target) {
for (int i = first; i < last; i++)
if (arr.equals(target))
return i;
return -1;
}
2.1这样看来好像Object的引用好像非常方便,而且第二个顺序搜索可以使用到float,double,String等等。
如果我们要进一步研究就会出现问题
- [/code]
-
- [b]public[/b] [b]static[/b] [b]void[/b] selectionSort([b]int[/b][] arr) {
- [b]int[/b] n = arr.length, smallIndex = 0;
- [b]for[/b] ([b]int[/b] i = 0; i < n; i++) { // 遍历array数组
- smallIndex = i;
- [b]for[/b] ([b]int[/b] j = i + 1; j < n; j++)
- [b]if[/b] (arr[smallIndex] > arr[j]) // 选择最小的索引j
- smallIndex = j;
- // if (smallIndex != i) {
- exchange(arr, i, smallIndex);// 交换
- // }
- }
- }
-
-
- 2.2上面的代码是一个顺序排序的算法,若果我们要写一个通用方法,就必须把object类型强制装换为一个
- 实现Comparable接口的方法。
- JVM在处理类型强制装换的时候就会,抛出一个警告:uncheck cast
- [code]
复制代码
@SuppressWarnings("unchecked")
public static void selectionSort(Object[] arr) {
int n = arr.length, smallIndex = 0;
for (int i = 0; i < n; i++) { // 遍历array数组
smallIndex = i;
for (int j = i + 1; j < n; j++) // 选择最小的索引j
if (((Comparable< Object>)arr[smallIndex]).compareTo(((Comparable< Object>)arr[j])) > 0)
smallIndex = j;
// if (smallIndex != i) {
exchange(arr, i, smallIndex);// 交换
// }
}
}
有此可以看出使用Object引用来处理通用问题,当使用实参如果没有实现Comparable接口,编译器会抛出一个castClassException的运行时异常。这样的程序是不安全的。
3.1使用Object引用来泛化一个算法(如顺序搜索)。通过使用数组的Object引用和目标值,
只要数据类型实现了equals方法,算法中要比较大小的数据类必须实现Comparable接口,
现在我们来用java泛型来解决这个问题
[code][/code]
public static < T extends Comparable<? super T>> void selectionSort(T[] arr){
int n = arr.length;
int smallIndex;
for (int i = 0; i < n-1; i++) {
smallIndex=i;
for (int j = i+1; j < n; j++)
if (arr[j].compareTo(arr[smallIndex])<0)
smallIndex=j;
exchange(arr, smallIndex, i);
}
}
在Arrays类中的静态方法 selectionSort(),这个方法处理的是整数类型。要用泛型版本来实现这个算法, 由于要泛型类型数组T[]中的两个元素要进行比较,所以传递实参的对象类型或其超类必须实现Comparable接口。 |
|