Consider the following code which uses the ability to intersect types, which was added in Java 8:
private <E, T extends List<E> & RandomAccess> void takeList(T list) {
}
private void fakingRandomAccess() {
List<Integer> linkedList = new LinkedList<>();
takeList((List<Integer> & RandomAccess)linkedList);
}
I have made a takeList method that only takes lists that have (near) constant access times, for whatever reason, but I can imagine that there would be situations where it is indeed warranted to do it such.
Passing an ArrayList<E> into the method should work just fine, however via type intersections you can also pass in a LinkedList<E> by pretending that it has constant access time.
Now my questions are:
- Is there any way to store
(List<Integer> & RandomAccess)linkedListin an object of a specified type? - Can I use type intersections to simplify the
takeListmethod?