Did you know that you can navigate the posts by swiping left and right?

Does Java 5 Generics give you better code?

28 Jan 2006 . tech . Comments #java #generics

I think I start to understand at least part of the Java 5 Generics now. I’m really not convinced that the benefit is worth the syntax and reduced readability. I’ll try to explain why…

I must confess that I see the point for the simple cases. In Java 1.4 the code for finding payments over a certain limit in a list of Payments would look like this:


public List findAllPaymentsOverLimit(List payments, int limit) {
    List overLimitPayments = new ArrayList();
    for(Iterator each = payments.iterator(); each.hasNext(); ) {
        Payment payment = (Payment) each.next();
        if (payment.amount > limit)
            overLimitPayments.add(payment);
    }
    return overLimitPayments;
}

And the bad thing is that we’ve all gotten used to that horrible casting syntax. With Java 5 we could change this function to something like this:


public List<Payment> findAllPaymentsOverLimit(List<Payment> payments, int limit) {
    List<Payment> overLimitPayments = new ArrayList<Payment>();
    for (Payment payment : payments) {
        if (payment.amount > limit)
        overLimitPayments.add(payment);
    }
    return overLimitPayments;
}

And that’s much better, right?

My problem is with the more advanced uses of this new tool. I’ll admit that I haven’t fully understood this, but if you want to create code that must accept a typed collection or even worse a map, you’ll have to learn the more advanced syntax where


    List<? extends Class>

or


    List<? super Class>

This is where it gets hairy, and where I start to think it might just not be worth it. On the other hand, I could leave that problem to the framework makers.