Amaynut
Amaynut

Reputation: 4271

Is the type parameter useful in the constructor of generic object instantiation?

I know that since Java 7, repeating the type of a generic class in the constructor during the instantiation is a redundancy. But how about the diamond operator <>, is it optionnal to repeat it? In other word, I would like to know what's the difference between this:

List<String> Fruits = new ArrayList<>();

and this

List<String> Fruits = new ArrayList(); 

or this

 Map<Integer, String> students = new HashMap<>();

and this

 Map<Integer, String> students = new HashMap();

Thank you in advance

Upvotes: 3

Views: 582

Answers (1)

rgettman
rgettman

Reputation: 178263

Yes, there is a difference. The diamond operator is just a shortcut for specifying the whole generic type, because it can be inferred. These are equivalent:

List<String> Fruits = new ArrayList<>();

and

List<String> Fruits = new ArrayList<String>();

However, with no angle brackets at all, that means you're using a raw type, which is different than using generics on the class. This generates an unchecked assignment warning, and it should be avoided.

List<String> Fruits = new ArrayList();  // warning!

Upvotes: 8

Related Questions