Good day.

As a person accustomed to C ++ and templates, I constantly have some misunderstandings with generics.

So, suppose we have printers that can print some objects:

public interface Printer<X> { public void print(X obj); } 

There is a list on which printer and what to print:

 class PrintInfo<X> { public Printer<X> printer; public X obj; } Queue<PrintInfo<?>> q; 

Now you want to start typing:

 PrintInfo<?> pi = q.poll(); pi.printer.print(pi.obj); // FAIL 

The problem is that for some reason Java does not see the emphasis, that this is a correct challenge, although the connection of types seems to be obvious. Please explain why this is happening, and what are the ways to get around it?


PS I went around by adding the print method to PrintInfo , which actually prints its object on its printer and calls it.

  • They are right there for you. - Alexander Kashpirovsky
  • 6
    @ Alexander Kashpirovsky it seems that you hypnotize me. - kirelagin

1 answer 1

Of course he does not see. This is due to "?". You are trying to take the unknown and print it with an unknown printer. But two different obscurity is not always compatible.

Perhaps this is a design error. Personally, it seems to me that generics are useless here.

UPD

OK. Maybe I lost my temper :)

In general, if you do not want to redo, then you can hide the seal inside Joba

 public class PrintTask<T extends Printable> { private final PrintStrategy<T> strategy; private final T object; public PrintTask(PrintStrategy<T> strategy, T object) { this.strategy = strategy; this.object = object; } public final void print() { strategy.print(object); } } 

And then you can just do

 do { queue.take().print(); } while (....); 
  • Yes, I understand that. But it would seem that PrintInfo contains enough information to ensure that these two uncertainties cannot be of different types ... - kirelagin
  • But there is also substituted "?" - cy6erGn0m
  • Oh, how stupid :(. Yes, this morning it looks much more obvious than it looked last night ... Give me back my C ++, in which such things work without problems! - kirelagin
  • In general, of course, this is a minimal example, and in the real task there are no printers, but I, like, quite accurately convey the essence of what is happening, so I am ready to discuss the idea with an error in architecture (to be honest, the interface corresponding to the printer is given initially, so I don’t have the opportunity to redo the architecture in this place, but simply out of sports interest). How to make without generics? - kirelagin
  • Yes, as I wrote in PS, that's exactly what I did;). Thank. - kirelagin pm