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.



September 21st, 2006 at 6:28 pm
Is it just me or does the whole syntax seem weird? Until 1.5 was there anything like this anywhere else in the language?
September 21st, 2006 at 8:21 pm
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.
February 5th, 2008 at 4:38 am
fine information, was very helpful for me, indeed
February 5th, 2008 at 8:14 am
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.
February 3rd, 2009 at 1:15 pm
Thank you very much. This was helpful.