RSS

Generic Comparators in Java

Sep 21, 2006    (Click to Rate!) Loading ... Loading ...

Technology


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.

Share and Enjoy:
  • Facebook
  • MySpace
  • Twitter
  • Digg
  • StumbleUpon
  • Reddit
  • del.icio.us
  • Propeller
  • Mixx
  • Fark
  • FriendFeed
  • Google Bookmarks
  • Suggest to Techmeme via Twitter
  • Slashdot
  • Technorati
  • Tumblr
  • Yahoo! Buzz
  • Print
, , ,

This post was written by:

Riyad Kalla - who has written 1727 posts on The “Break it Down” Blog.

"Ultimately I just want to provide a resource that folks find useful."

5 Comments For This Post

  1. Ben Says:

    Is it just me or does the whole syntax seem weird? Until 1.5 was there anything like this anywhere else in the language?

  2. Riyad Kalla Says:

    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.

  3. HC Says:

    fine information, was very helpful for me, indeed

  4. Riyad Kalla Says:

    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.

  5. Anu Says:

    Thank you very much. This was helpful.

Leave a Reply