Wednesday, 4 September 2013

Restrict method to RandomAccess List

Restrict method to RandomAccess List

I've a method that operates on a List, removing certain duplicates. The
algorithm is only efficient on lists implementing RandomAccess. To prevent
misuse and disappointing performance, I'm wondering how to enforce the
RandomAccess restriction. The RandomAccess interface does not extend List
unfortunately, so I sort of need to make the variable be two types at
once.
I could declare the method to accept ArrayList rather than List, but other
list types can implement RandomAccess too (for example, the lists returned
by Collections.synchronizedList and Collections.checkedList), and I don't
want to block those.
I tried generics, but couldn't construct a working syntax:
public <T> void process(<List<T> extends RandomAccess> list) {
...
}
I could do:
if (!(list instanceof RandomAccess))
throw new UnsupportedOperationException("RandomAccess list required");
But then the restriction is only enforced at run time, which is less robust.
Help?

No comments:

Post a Comment