以下是通用搜索算法的实现:
界面:
public interface Comparable<T extends Comparable<T>> {
int compare(T arg);
}
CompareSort.java
public abstract class CompareSort<T extends Comparable<T>> {
protected boolean less(T v, T w) {
return (v.compare(w) < 0);
}
protected void swap(T[] args, int i, int j) {
T swap = args[i];
args[i] = args[j];
args[j] = swap;
}
public abstract void sort(T[] args);
}
算法之一:
public class SelectionSort <T extends Comparable<T>> extends CompareSort<T> {
@Override
public void sort(T[] args) {
int N = args.length;
for (int i = 0; i < N; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (less(args[j], args[min])) {
min = j;
}
}
swap(args, i, min);
}
}
}
最后是一个对字符串进行排序的主要方法。
public class StringSorter {
public static <T extends Comparable<T>> void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<String>();
int i = 0;
while (i < 10) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
list.add(str);
i++;
}
String[] a = list.toArray(new String[list.size()]);
// Create a sort object, use it on a, and print the sorted array.
SelectionSort<String> selection = new SelectionSort<String>();
selection.sort(a);
for (i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
问题在于:
SelectionSort<String> selection = new SelectionSort<String>();
绑定不匹配:String类型不是SelectionSort(T)类型的有界参数(T extends Comparable(T))的有效替代
(方括号=弯曲括号)
问题出在哪里?我想不明白... 通用参数T也被扩展。
答案 0 :(得分:5)
而不是创建Comparable
不实施的String
,而是使用Java java.lang.Comparable
,String
执行< / strong>实施。