Reputation: 33
Here is a implementation of a generic search algorithm:
The interface:
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);
}
One of the algorithm:
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);
}
}
}
And finally a main method to sort Strings.
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]);
}
}
}
Here is the problem:
SelectionSort<String> selection = new SelectionSort<String>();
Bound mismatch: The type String is not a valid substitute for the bounded parameter (T extends Comparable(T)) of the type SelectionSort(T)
(box brackets = curved brackets)
Where is the problem? I can not figure it out... the generic parameter T is extended as well.
Upvotes: 0
Views: 162
Reputation: 279940
Instead of creating your own Comparable
, which String
does not implement, use Java's java.lang.Comparable
, which String
does implement.
Upvotes: 5