0

The following code:

Set<? extends Integer> set = new HashSet<>();

Compiles fine. However, the essence of using the diamond notation is just for not rewriting the LHS type parameter again. This means that the statement above should be equivalent with the following:

Set<? extends Integer> set = new HashSet<? extends Integer>();

But as it turns out, it's not. I guess it's rational since the compiler doesn't know the object's type parameter since it's the wildcard ('?'). When not using bounded type parameters, everything works fine so I supposed the same would apply for any case. But why allow the syntax anyway? What is, in the end, the type parameter of the first statement?

Thanks

Some1
  • 103
  • 6
  • See if these Q&As help with understanding generics: [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super), [Difference between super T> and extends T> in Java](https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java), and [Creating new generic object with wildcard](https://stackoverflow.com/questions/9147129/creating-new-generic-object-with-wildcard). – Slaw Jan 09 '21 at 12:22
  • This question may even be a duplicate of the last one I listed. – Slaw Jan 09 '21 at 12:22
  • See also: https://softwareengineering.stackexchange.com/questions/194107/why-it-is-not-possible-to-instantiating-types-with-wildcards-in-java – Sweeper Jan 09 '21 at 12:25
  • Set extends Integer> set = new HashSet extends Integer>(); The above statement is not allowed, as the HashSet Object need to be of a concrete type, not a wildcard or generic. Below would be valid expressions: Set extends Integer> set = new HashSet(); Set extends Number> set = new HashSet(); Set extends Number> set = new HashSet(); Set extends Number> set = new HashSet(); – Prateek Pande Jan 09 '21 at 12:28
  • Also, Set extends Integer> set = new HashSet<>(); is a valid expression as compiler will infer the HashSet type. But with new HashSet(); the compiler is stuck with the wild card and not an actual Object type and there is no scope for the compiler to infer. – Prateek Pande Jan 09 '21 at 12:37

0 Answers0