hatellla
hatellla

Reputation: 5142

Set without Datatype mentioned

Is it fine to write following?

Set<Integer> integs = new HashSet<>();

Inside <>, is it fine to leave it as empty?

Upvotes: 7

Views: 845

Answers (4)

Rajesh
Rajesh

Reputation: 384

Yes. In your case, It'll take it as integer in Java 7 and later versions. Please find the confirmation from the Java documentation. http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 27001

Yes if you're using java 7 or higher as described in 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. This pair of angle brackets is informally called the diamond.

Upvotes: 2

M A
M A

Reputation: 72884

Yes this is a feature introduced in Java 7 where the <> is called the diamond operator. See http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html.

Upvotes: 3

npinti
npinti

Reputation: 52185

As from Java 7, the compiler will infer the data type of the hash set without the need to write it twice.

Note though that there are some scenarios where the compiler might fail to infer the type, so you could get compilation errors for more complex scenarios.

More of that here.

Upvotes: 3

Related Questions