ArrayList declaration with type or without

6

I would like to know the difference in declaring a ArrayList like this:

List<BancoPerguntas> listaBancoPerguntas = new ArrayList<BancoPerguntas>();

List<BancoPerguntas> listaBancoPerguntas = new ArrayList<>();

In the second example I do not pass the entity in ArrayList .

Is there a difference?

    
asked by anonymous 31.03.2018 / 03:08

2 answers

6

The two codes are equivalent. The second form with diamond ( <> ) was introduced in Java 7 in order to make the generic type syntax leaner, avoiding the redundancy of having to declare the generic type both in the invocation of the constructor and in the type declaration.

When the compiler finds the diamond, it looks at the variable declaration to find out what should be put there. This way, the compiler transforms the second form into the first.

There is also a third way introduced in Java 10:

var listaBancoPerguntas = new ArrayList<BancoPerguntas>();
    
31.03.2018 / 03:45
6

It has already been said that it is the inference and I think you can infer (pun intended) in the comments that it is just a syntactical difference without affecting semantics, performance or any other question.

What you're doing in the second example is just omitting something the compiler already knows, it just is not written, but the information is still there.

In Java 10 you can do different in local variables:

var listaBancoPerguntas = new ArrayList<BancoPerguntas>();

Again% w / o% does not change anything, the compiler reads what is on the right side of the expression and sees that it does an assignment and through it the type can be determined even without being explicitly written in the place it should. Think about it, why would you type the same thing twice?

You can also do:

var x = 1;

and

var y = retornaUmInt();

But we do not usually recommend this last case because it is less readable to know what type is the variable.

There are cases that you can not use the inference, because the variable type must be different from the / literal constructor type.

It is very complicated to do the same for instance variables, so it is not allowed.

Java is improving:)

    
31.03.2018 / 03:45