Sorting an array in JDK 5.0 using generics.
Remus Stratulat 2005-09-27
Generics java sorting.Java 5.0 introduces a new concept called generics. This is very helpful especially when using collections. Because of the generics concept, a programmer can now avoid a lot of bugs generated by the insertion of a wrong type inside a certain collection and can avoid a lot of explicit casting. To avoid this types of bugs in the old versions, wrappers must be constructed with proper setters and getters. Now all this "defensive" programming is replaced by a small syntax addition:
List<MyClass> aList = new ArrayList<MyClass>();
Now everything is nice and simple when writing code:
MyClass a = aList.get(i);
But the generics concept is not limited only to this. There are also generic methods. I hit the wall of generic methods the first time I've tried to sort an array. The sort method definition is as follow:
public static <T> void sort(T[] a, Comparator<? super T> c);
I will not enter into details of what
<? super T> means, this topic about wildcards is covered in an article found here:
http://java.sun.com/developer/technicalArticles/J2SE/generics/But because the new definition of the Array.sort() method I received an warning from the compiler:
Unchecked invocation sort(Object[], Comparator) of the generic method sort(T[], Comparator<? super T>) of type Arrays.
Now you can decide to ignore that and add
@SuppressWarnings("unchecked") above your method definition to not receive the warning any more. But you can also try to solve the problem as if you are using 5.0 maybe you should use it all the way.
The code was as follow:
public void myMethod() {
MyClass[] arr = getAnArrayOfMyClass();
Comparator c = new MyClassComparator();
Arrays.sort(arr, c);
}
private class MyClassComparator implements Comparator {
public int compare(Object o1, Object o2) {
MyClass a1 = (MyClass)o1;
MyClass a2 = (MyClass)o2;
return a1.getString().compareTo(a2.getString());
}
}
The same code will become in JDK 5.0:
public void myMethod() {
MyClass[] arr = getAnArrayOfMyClass();
MyClassComparator c = new MyClassComparator();
Arrays.sort(arr, c);
}
private class MyClassComparator implements Comparator<MyClass> {
public int compare(MyClass o1, MyClass o2) {
return o1.getString().compareTo(o2.getString());
}
}
Actually the code becomes simpler in 5.0 style.