Why can this happen in a foreach?

7

I built two simple classes:

import java.util.ArrayList;
import java.util.List;

public class Aluna {
   String nome;
   String idade;
   String cpf;

List<Aluna> listar(){
  ArrayList<Aluna> aluns = new ArrayList<>();
  Aluna aluna;

 aluna = new Aluna();
 aluna.cpf="839457476";
 aluna.idade="30";
 aluna.nome="Tereza ";
 aluns.add(aluna);

 aluna = new Aluna();
 aluna.cpf="89437298472";
 aluna.idade="17";
 aluna.nome="Aline";
 aluns.add(aluna);
 return aluns;
  }
}

 public class Start {

   public static void main(String[] args) {

    for(Aluna al : new Aluna().listar()){
        System.out.println(al.cpf);
        System.out.println(al.idade);
        System.out.println(al.nome);
        System.out.println("------------------------");
    }
  }
}   

I was doubtful of the excerpt in the code:

        for(Aluna al : new Aluna().listar()){

I know it's a foreach and it lists data. But instantiating a class and having access soon to its method in the class inside the foreach I found strange. How do you call this kind of thing?

Ps : Do not take into account the lack of encapsulation.

    
asked by anonymous 14.02.2016 / 17:34

2 answers

9

Regardless of foreach what is happening is the use of a value without needing a variable.

Contrary to popular belief, a variable is not always necessary. The variable is just a way of storing a value. You can work with values directly. Of course there are situations where it is desirable to store a value for later use.

Then the code

new Aluna().listar()

could be written as

Aluna aluna = new Aluna()
ArrayList<Aluna> alunas = aluna.listar()

and using no for

for (Aluna al : alunas) {

But why create these variables? What do they add to the code? Anything! Then the code used in the question instantiates the class and instead of storing the object generated in the instantiation, it is immediately used to call the listar() method which in turn returns a ArrayList to the foreach iterate. p>

In fact there are some problems in this class and it is not just the encapsulation. Okay to do this quickly to exemplify, but a Aluna should not accumulate a list of students. Note how strange it is to have a list of students within a student.

    
14.02.2016 / 18:00
4

The foreach waits for a list of elements to undergo iteration.

If the method to be invoked is signed to return a list, there is no breach of contract between the mechanisms involved.

When you instantiate your class Aluna and then call your method, it will be that method that will be in charge of supplying the list that foreach expects.

If there are any gaps left in the clarification, please post in the comments.

    
14.02.2016 / 17:44