Reputation: 325
I have an exercise to solve but I can't get my head around it. So the question is: The following program prints a sequence of strings in ascending order. Observe that sort sorts arrays of strings only. Rewrite it so that it sorts objects of type T, where T is introduced in the sort header as a generic type name, and T implements Comparable. Changes should be limited to modifying the header and body of sort. So the code I'm given is:
class SortNames {
static void sort(String[] s) {
for (int i = 0; i<s.length; i++) {
for (int j = i+1; j < s.length; j++) {
if (s[i].compareTo(s[j])>0) {
String t;
t = s[i]; s[i] = s[j]; s[j] = t;
}
}
}
}
public static void main(String[] args) {
String[] names = {"Pete","Jill","May","Anne","Tim"};
sort(names);
for (String s:names){
System.out.println(s);
}
}
So what I did is:
class TestSort{
static void sort(T[] s) {
for (int i = 0; i<s.length; i++) {
for (int j = i+1; j < s.length; j++) {
if (s[i].compareTo(s[j])>0) {
Object t;
t = s[i]; s[i] = s[j]; s[j] = t;
}
}
}
}
public static void main(String[] args) {
int[] numbers = {3,6,2,7,9,1,8};
sort(numbers);
for (int a:numbers){
System.out.println(a);
}
}
Now when I compile my code, I get:
TestSort.java:3: error: cannot find symbol
static void sort(T[] s) {
^
symbol: class T
location: class TestSort
1 error
What is wrong? :( Can anyone recommend me some good source for reading? I have exam on that tomorrow :( Thanks in advance!
Upvotes: 1
Views: 77
Reputation: 178263
You need to define your generic variable T
on your sort
method to make it generic. The T
as the datatype merely refers to the generic type parameter.
static <T extends Comparable<T>> void sort(T[] s) {
Upvotes: 4