0
votes

(nevermind:) it's illegal: HashSet<> f;

it's legal: new HashSet<>();

From type inference documentation:

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context.

But a compiler cannot infer type argument in second example, so why does it compile?

1
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters That's not what you're doing in your first snippet.Sotirios Delimanolis
Also, it can infer. It infers Object. That rules of type inference are extremely long, but that's what new HashSet<>() reduces to.Sotirios Delimanolis
What gives you the impression that the compiler cannot infer type argument in second example?Software Engineer
@EngineerDollery I thought that inferring works only when there is already some code which defines generic type and then you don't have to repeat yourself in next statements. I thought that when there is no such code, then there is no context to use for inferring. But now I see inferring is a broader thing.ctomek

1 Answers

1
votes

Generics is a compile-time construct. That is, it's used to enforce that a given variable or method can only work with a specific type or set of types. In your case the compiler can "infer" the broadest type - Object, since the HashSet is not being assigned or returned, so the types will never be used at compile time. And at runtime the types are meaningless due to type erasure.