Generics support for Apache commons collections

In my day to day work program I use the Apache Commons library quite a lot.  One of those libraries is the commons collections library, of which I use the CollectionUtils class and ListUtils mostly. One great disadvantage of the commons collection library is lack of Java Generics support, added in Java 1.5.  This means if you call a function like predicatedList with a typed list and predicate argument, the function will return an untyped list. The list has to be cast again, which clutters up the code and doesn’t look very nice, like the following example:

class Address {
    String firstName;

myAddresses ; ... List
onlyJohns = (List
) ListUtils.predicatedList(myAddresses,new Predicate() { public boolean evaluate(Object o) { Address a=(Address)o; return a.firstName.equals("John"); } });

Quite a lot of casting as you can see in the above code. Less code would be needed if generics support would be added to the collection framework. Added generics support to the collections library should be too hard, and would improve my code.

I’d think other people would have that idea, and I quickly found the following posting on devx. Turns out there’s a sourceforge project that has modified the collections library to have generics support: Commons Collections with generics.
The project is even added to the central maven repository, so to use the new collection library adding the following dependency is enough:


The new code now becomes (excluding the Address class, which is the same):

onlyJohns = ListUtils.predicatedList(myAddresses,new Predicate
() { @Override public boolean evaluate(Address a) { return a.firstName.equals("John"); } });

The code looks quite better! A lot less code would be needed if closures would be added to Java too, but that’ll have to wait until JDK 1.8 or something is released.

Sr Software Consultant

Geplaatst in Technology Getagd met ,