0

I have noticed that below code is completely legal in netbeans:

HashSet<String> hashSet = new HashSet<>();

However eclipse is not happy with that, and I have to initialize it like this:

HashSet<String> hashSet = new HashSet<String>();
// or
HashSet<String> hashSet = new HashSet();

And interestingly netbeans suggests to not specify the type parameter in the initialization part and instead use diamond operator?? I want to know what is the difference between these two approaches. And which one should someone use, so that code can be used in different IDEs without any change.

Mustafa Shujaie
  • 1,447
  • 1
  • 16
  • 30
  • 5
    Your Eclipse language level is set to 6 or lower not allowing the diamond operator `<>` introduced in Java 7. – user432 Aug 13 '15 at 16:04

4 Answers4

4

The diamond <> is used for Generic Type Inference, a feature introduced in Java 7.

List<String> list = new List<>();

Doing this requires the compiler to be "smart", and figure out that what you really mean is:

List<String> list = new List<String>();

This is why it didn't exist when generics first came into being in Java 5. It was later added as syntactic sugar in Java 7.

durron597
  • 31,968
  • 17
  • 99
  • 158
3

Java 7's Generic Type Inference

From Oracle's 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. For example, consider the following variable declaration:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap()constructor refers to the HashMap raw type, not the Map<String, List<String>> type:

Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning

Keith
  • 3,079
  • 2
  • 17
  • 26
2

<> is Just syntactic sugar when the full generic type can be derived from the variable declaration.

List<Integer> list=new ArrayList<>();

In this case the type is clear from the declaration. Valid from java 1.7 and onwards. Set your IDE to the correct version (or your maven project).

Jilles van Gurp
  • 7,927
  • 4
  • 38
  • 46
1

As user432 stated, your eclipse compiler compliance level is likely set too low. The diamond operator was not introduced until Java 1.7.

To fix this, open Window > Preferences > Java > Compiler and set the Compiler compliance level to 1.7 or higher.

gla3dr
  • 2,179
  • 16
  • 29