I think your interpretation of what the code is is wrong. You’re probably not thinking about how he’s executed, I imagine you think you put words in and magically something happens. Everything that is written has a consequence and it is necessary to understand the whole process, otherwise it will not learn to program.
Let’s understand what happens with the list:
On the line
List<String> lista = new ArrayList<>();
a list of strings and is referenced by a variable called lista
.
On the following lines
lista.add("Aline");
lista.add("João");
lista.add("Jona");
lista.add("Pedro");
elements are added to this list.
Finally on the line
return lista;
the list is returned to the caller. The variable lista
ceases to exist, but the object pointed out by it, in case the list with 4 elements still exists and will be pointed out by the one who called this method.
We now return to the main method. On the line
Teste1 t = new Teste1();
an object of the type Teste1
and placed in the variable `t . Actually, there wouldn’t have to be an object just for this, but come on.
On the line
dados = t.getList();
the method is called and its return, that our list is passed to the variable data that had already been declared. So now dados
now has the list that was in the variable lista
within the method getList()
.
Finally the line
System.out.println(dados);
prints the list.
I put in the Github for future reference.
You don’t need another new
anywhere because you only need to create the list once. You have nothing to "accumulate" because the code does not command you to do this. If he had it done then he would. It would be impossible to have [Aline, João, Jona, Pedro Aline, João, Jona, Pedro, Aline, João, Jona, Pedro]
because only a list with only 4 elements was created.
You have to understand what the code is doing or you keep repeating code ready and you don’t know what you’re doing.
I imagine you want to do something else, but the question doesn’t even mention it. Before programming, it is necessary to understand the problem and express it in Portuguese. If this cannot be done, it is certain that in Java it will not be right, since the base is wrong.
Why do you have a
main()
insideTeste1
? Set "accumulate". Can’tnew
?– Maniero
It’s like the start of my code.
– Aline
It doesn’t seem to make sense. Which of the two is the
main()
in fact? Alias, what is the doubt?– Maniero
My question is why I do not need to give new in the data list? And why it does not accumulate???
– Aline
accumulate is like doing this with the given list: [Aline, John, Jona, Peter Aline, John, Jona, Peter, Aline, John, Jona, Peter] to each run more on the list
– Aline
This you’ve already written, now explain what this means.
– Maniero