generics: filter a Collection but at the same time bound it to RandomAccess

I would understand if the failure would occur if RandomAccess would take a type parameter. But it does not, so (at least in my understanding) it should not influence the resolution of T.

It does not. The problem with filter(List.of(1,2,3), x -> x > 1); is that the static type of the expression List.of(1,2,3) is not a subtype of RandomAccess, and that’s rejected because it does not meet the extends RandomAccess constraint.

Both of the following compile with no problem, with the inference of T remaining unaffected

filter(new ArrayList<>(List.of(1, 2, 3)), x -> x > 1);
filter(new ArrayList<>(List.of("a", "b", "c")), x -> x.length() > 1);

Simply because ArrayList is both a Collection and RandomAccess subtype. I guess, however, that depending on your compiler implementation, you have one of many flavors of unhelpful error messages (like The method filter(M, Predicate<T>) in the type Main is not applicable for the arguments (List<Integer>) on filter(...) and Type mismatch: cannot convert from List<Integer> to M on List.of(...) in Eclipse)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top