Why can this happen in a foreach?

Asked

Viewed 327 times

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 left with doubt 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 to its method right in the class within the foreach I found strange. How could they do that kind of thing?

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

  • What kind of thing? Make a method call? I didn’t quite understand the doubt.

2 answers

9


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

Contrary to what many think a variable is not always necessary. The variable is just a way to store a value. You can work with values directly. Of course there are situations that it is desirable to store a value for later use.

So the code

new Aluna().listar()

could be written as

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

and using in the for

for (Aluna al : alunas) {

I put in the Github for future reference.

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

In fact there are some problems in this class and it is not only encapsulation. Ok 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.

  • 1

    But Arraylist implements List. Apparently the signature is list and returns an arraylist does not generate error.

  • 1

    Exactly, @Diegofelipe. No error can be generated if the class has an implementation contract with the one specified in the return signature.

  • 1

    @Diegofelipe is true, a lot of language, confuses everything :)

  • Okay. Did you find this strange @bigown? What I could store in a Student arrayList then?

  • @Alinegonzaga should be another object, perhaps, and only perhaps another class. Try to explain why a student might have several students inside her? Isn’t it strange? Think of objects as real things. If the relationship seems absurd in an object, it’s because there’s something wrong.

  • I can’t understand that. It’s a lot of abstraction for me... Do you think about the level of how to put this in the bank?

  • Yes, abstraction is a complicated thing. To keep in the bank is something very concrete. But in this case there is nothing bank there, I’m talking only of this code. Everything you put in the code has to have a justification. If you can’t find one, you’re wrong. What is your justification for placing a STUDENT LIST within a STUDENT?

  • Why don’t you tell me a solution to this?

  • Simple, take from inside the student. Anywhere else get better. I can’t say where because I don’t know what this is about, I can only talk about what I’m seeing.

  • 1

    @Alinegonzaga This model Student.() is part of a Pattern called Active Record, which uses the concept that the class representing a type of entity takes care of all behaviors relating to that type of entity, including its persistence and recovery. An example of a highly respected tool that uses this Pattern is Ruby On Rails. In this case, it is incorrect to say that there is a "list of students within a student" because we are not talking about a student but about the class that represents entities of this type. A student would be an instance object of this class, and not the class itself.

  • 1

    @Alinegonzaga There is however a current of thought that believes that a class representing a type of entity should have only the business behaviors of that entity, and implementing persistence and recovery would be too much responsibility for a single class, should therefore be delegated to another object (a repository, for example).

  • @Alinegonzaga Notice that the method list and other recovery methods need to be static class methods Student so that they belong to the class instead of belonging to the object. Already the methods of persistence and removal ("salvage", "delete"), in Pattern Active Record, they belong to the actual object (they are same instance methods).

  • Then I study what you’re talking about @Caffé. It’s just that I’m having some mistakes here in my project in . jsp.

Show 8 more comments

4

foreach waits for a list of elements to be iterated.

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

When you urge your class Aluna and soon after make the call to your method, it will be that method that will be in charge of providing the list that foreach awaits.

If there is still a gap in the clarification, put in the comments.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.