Consider you have this List:
private final List<? extends AbstractXmlElement> inMemoryElements;
that contains a bunch of objects of subclasses of AbstractXmlElement and you want to add a method to filter objects of a specific subclass from that list. For this I created the following method:
public <E extends AbstractXmlElement> List<E> getInstancesOf(Class<E> c) {
return getUsableElements().stream()
.filter(c::isInstance)
.map(e -> (E) e)
.collect(Collectors.toList());
}
Yet (E) e results in an UncheckedCast Warning. I was wondering how exactly this is an unchecked cast and if it is safe to suppress this warning since those objects that are not an instance of E are filtered out before the cast. Meaning that, as far as I know, the cast should never fail
It's an unchecked cast because the type of
Eis unknown at runtime. Since you're checkingisInstance(), your code is safe. But if you want to avoid the warning, you can usecto do the cast: