> In the below code, argument type of compare() method is declared
> as String.
Not exactly!
> However, compiler emits the error:
>
[quoted text clipped - 5 lines]
> user layer. Could someone help writing a String specific Comparator
> class properly?
> 10: Arrays.sort(sa, new IndexComparator<String>("ba"));
> 15: static class IndexComparator<String> implements Comparator<String>{
In this context, "String" does not refer to the class java.lang.String.
When you place <T> after the name of the class in the class declaration,
you are creating a generic class, with the generic type parameter <T>.
You can use whatever identifier you want there: <T>, <Type> or <String>.
So you are defining a generic class IndexComparator, one that can be used
with Strings, Dates, or whatever. I do not think that is what you want.
Try removing the <String>:
> 10: Arrays.sort(sa, new IndexComparator("ba"));
> 15: static class IndexComparator implements Comparator<String>{

Signature
Regards,
John McGrath
hiwa - 01 Apr 2005 00:43 GMT
> > In the below code, argument type of compare() method is declared
> > as String.
[quoted text clipped - 28 lines]
>
> > 15: static class IndexComparator implements Comparator<String>{
Thanks John. It now works perfectly.
The result seems for me to have used only the shallowest part
of Java generics. :)
-------------------------------------------------------------
import java.util.*;
public class IndexSort{
public static void main(String[] args){
String[] sa
= {"abasa", "dwapba", "oobaon", "balsa", "eglengelbao", "sveembat"};
Arrays.sort(sa, new IndexComparator("ba"));
System.out.println(Arrays.deepToString(sa)); // JDK 1.5
}
static class IndexComparator implements Comparator<String>{
String str;
public IndexComparator(String subs){
str = subs;
}
public int compare(String o1, String o2){
return o1.indexOf(str) - o2.indexOf(str);
}
}
}
--------------------------------------------------------------