0

Recently, I saw the following constructor call:

Set<String> s = new HashSet<>();

I was surprised that one can call the constructor of the generic class HashSet with empty parentheses < and >. What does this mean?

John Threepwood
  • 15,593
  • 27
  • 93
  • 149
  • Read more here: http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html – vegaasen Feb 16 '17 at 12:29

2 Answers2

2

Since you've already declared what type of value (String in this case) the Set will hold, repeating it is redundant.

Zetta
  • 21
  • 1
  • Thank you. So `new HashSet<>()` is just a shortcut writing for `new HashSet()`? – John Threepwood Feb 16 '17 at 12:30
  • @JohnThreepwood I think it shouldn't be considered a shortcut, because repeating the generic type in the `new` is completely pointless, so there is no need for shortcuts to get to that. It would be like saying that `1 + 1` is a shortcut for `1 + 1 + 0`. Eclipse has a warning when you do that: `Redundant specification of type arguments `. – SantiBailors Feb 16 '17 at 13:27
1

this is diamond syntax, introduced since java7

reference: https://dzone.com/articles/java-7-do-we-really-need

Elias
  • 664
  • 2
  • 11
  • 23