0

let me give you an example (client-server communication), let's say we have the following class:

public class Message<Data, From extends Connectable, To extends Connectable>

Connectable is an interface that both the client and server implements. My question is when creating an instance of Message do I have to add <?, ?, ?> to the type?

Message<?, ?, ?> m = new Message<>(...);

or

Message m = new Message<>(...);

I know <?> is a wildcard shortcut for <? extends Object> I just don't get when do I have to add this? Is there any difference? Thanks!

Nati
  • 21
  • 1
  • Does this answer your question? [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) – 时间只会一直走 Dec 30 '22 at 09:00

1 Answers1

0

You never need to add <?>, but in new code you always should add it (for generic classes). Basically, the <?> tells the compiler that you know about generics and want the strict type checking that comes with it.

However, usually you will not use <?> but a more specific type parameter:

Message<String, SourceConnectable, TargetConnectable> m = new Message<String, SourceConnectable, TargetConnectable>(...);

or, employing type inference features of newer Java versions:

Message<String, SourceConnectable, TargetConnectable> m = new Message<>(...); // Java 1.7+
var m = new Message<String, SourceConnectable, TargetConnectable>(...); // Java 10+
Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • @user16320675 Yes, that "in new code" should also apply to that, of course. But I removed the sentence. It doesn't really say what I wanted to say with it, and it wasn't necessary for the answer. – Hoopje Dec 30 '22 at 14:34