Question

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?

Was it helpful?

Solution

You need to use multiple bounds, indicated by an ampersand (&):

public <T,L extends List<T> & RandomAccess> void process(L  list)

Putting it into a (non-compilable, unless you remove the second call) class:

public class Main {

    public static void main(String[] argv)
    throws Exception
    {
        Main x = new Main();
        x.process(new ArrayList<String>());
        x.process(new LinkedList<String>());
    }

    public <T,L extends List<T> & RandomAccess> void process(L  list) {

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top