Parameter type parameterized does not work in a loop

I have these types:

abstract class ControlGraphic { //... } class PrecisionControlGraphic extends ControlGraphic { //... } class AccuracyControlGraphic extends ControlGraphic { //... } 

I have a method that returns List<T> , where T is PrecisionControlGraphic or AccuracyControlGraphic depending on the type parameter:

  private <T extends ControlGraphic> List<T> getGraphics() { List<T> graphics = new LinkedList<T>(); for (ControlGraphic graphic : getGraphicsFromDB()) graphics.add( (T) graphic); return graphics; } 

The code below works correctly:

 List<PrecisionControlGraphic> precisionGraphics = getGraphics(); for (PrecisionControlGraphic graph : precisionGraphics) { ... } 

I would like to know why this other is not:

 for (PrecisionControlGraphic graph : getGraphics()) { ... } 

Thanks.

+6
source share
1 answer

The method signature says "you can set T to any ControlGraphic subclass", and therefore the purpose of typechecks (because the compiler finds a type T that works, in fact the type is taken from the assigned variable).

The "other" (direct loop) does not work, because type T can be any subclass of ControlGraphic, not necessarily PrecisionControlGraphic. The direct loop does not work, because type checking in Java does not make full output, as in functional programming languages. The variable type “graph” would literally have to be “any subclass of ControlGraphic” in order for it to be accepted (and this could actually be organized by making the type a parameter of the type of the attached method).

Another possibility, as @Adrian Leonhard pointed out, is to annotate a getGraphics call with the type you want:

for (PCG graph : this.<PCG>getGraphics())

But, basically, with any of these solutions you are abusing generics. All you know about getGraphics is that you are dealing with ControlGraphic objects, and so the method should return a List<ControlGraphic> , and your code should explicitly cast in places in the code that the derived type is known for.

+5
source

Source: https://habr.com/ru/post/984605/


All Articles