Are you using generics in Java? Are you trying to execute a Collections.sort method call and getting an “unchecked” warning from the compiler? This is something I just had to battle with, and here’s how you do it correctly.
First your Comparator needs to specify that it is of the type you will be comparing (in my case, JSF SelectItems), like so:
private static class CountryCodeComparator implements Comparator<SelectItem>; { public int compare(SelectItem item1, SelectItem item2) { return item1.getLabel().compareTo(item2.getLabel()); } } |
And then you have to make sure your List is of the necessary type when you create it:
List<SelectItem> countryCodeList = new ArrayList<SelectItem>; |
Then you just make your Collections.sort call with no worries:
Collections.sort(countryCodeList, new CountryCodeComparator()); |
I found this resource which was very helpful in this regard.

Is it just me or does the whole syntax seem weird? Until 1.5 was there anything like this anywhere else in the language?
Dear Ben,
May be the use of the Generics give you some of the awkard syntax to implement but at the end it saves you from lot of trouble.
Before JDK1.5 there was no sign of generics in java,but c++ implements use this as the name of template…
This was a complaint a lot of people had and one reason I didn’t get into generics until about 3 months ago. After using them they make more sense and in about 4 occasions I have hit compile-time errors that I hadn’t noticed that would have been sucky runtime errors to track down. I think overall it’s a good thing. One of the bigger points of them was just to get more validation into the compiler-phase of the application. There is a ton of attention being paid to improving the overall stability of the language moving forward with stuff like this.
I can’t say I love autoboxing, it makes things sloppy-easy in my experience, but for the few times where you do get to pass an int as an object or treat and Integer like an int, it’s pretty slick. I just feel wrong doing it, so I actively have Integer.valueOf(i) calls around my code when I need to convert.
I’m sure I’ll drop that habit at some point.
fine information, was very helpful for me, indeed
HC, I’m glad it helped. I always run into issues when I get into Generics and have to go digging/Googling for answers.
I’m happy to hear this helped you out.
Thank you very much. This was helpful.
Thanks!
Most welcome!
This post is most welcome; thank you.
Thanks, that was just what I needed.
Thanks, that was just what i needed [2].
Cleiton, glad it helped!
Tnx! I’m pretty new with generics, and this makes sorting a lot easier!
Glad it helped.