When is specifying generic types for collections necessary?

jhud :

The following lines of code each compile (in separate methods, of course):

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

Is one of these encouraged over the others? Are there any differences in behavior between these options?

Vinay Prajapati :

<> is called diamond operator and it determines the type from Reference variable declaration.

Recommended is using diamond operator as this avoids boilerplate or duplicate declaration of type variable as it's clearly visible from the Declaration of variable while allowing a type to default to Object class type if not specified.

All the three above are valid except List<String> list = new ArrayList(); giving a warning or simply not considered a good practice.

my thoughts: List<String> list = new ArrayList(); could also have been a valid declaration from that perspective but it defaults to array list of Object type (that's how Java is). Precisely:

if you don't specify a type, it defaults to Object type

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327713&siteId=1