How to use foreach to print information from an object array? (Java)

Asked

Viewed 620 times

1

Good night!

I have this structure below and would like to know how I could use a for each to print the information of this vector.

public static void main(String[] args) {
    Scanner teclado = new Scanner(System.in);

    Funcionario funcionarios[] = new Funcionario[5];

    String nome;
    double salario;

    for (byte i = 0; i < 2; i++) {
        System.out.println("informe o nome: ");
        nome = teclado.nextLine();

        System.out.println("informe o salario");
        salario = Double.parseDouble(teclado.nextLine());

        Funcionario f;
        f = new Funcionario();
        f.nome = nome;
        f.salario = salario;

        funcionarios[i] = f;
    }

    //Este código abaixo foi uma tentativa, não entendi como ele funciona
    for(Funcionario f1 : funcionarios){
        System.out.println(f1);
    }

    }
  • Hi Lucas, your loop is right. What’s the question? Do you want to know how this loop is working?

1 answer

4


Probably, when you run this code, the output is something like this:

Funcionario@28d93b30

This has nothing to do with loop, and, it occurs because you are printing an object, not primitive types as a int, float, etc. When you call System.out.println(f1); he will seek by the method toString employee class. Hence you think: "I have no 'to string' method in this class".

In Java, every class is subclass of Object implicitly, imagine that there is a extends Object even against his will (:P). And if you look at the implementation code, will see that Object has some methods and the toString is one of them, that is, whenever you create a class, this method will be present.

If you don’t override the method, superclass code will be called. And its implementation is as follows::

public String toString() {
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This is the name of the class followed by the @ and the hexadecimal code of hashcode of the object.

Then, responding, you can access the attributes of this object:

for(Funcionario f1 : funcionarios){
   System.out.println("Nome: " + f1.nome + ", Salário: " + f1.salario);
}

Or do what (in my opinion) is much simpler: overwrite the method toString:

public class Funcionario {

    public String nome;
    public double salario;

    @Override
    public String toString(){
        return "Nome: " + nome + ", Salário: " + salario;
    }
}

Thus, in calling System.out.println(f1) the code that was defined in the employee class will be executed and you will have a "more readable" output for humans.

  • Good evening! Yes, I actually decrease the number from 5 to 2 for testing only. Thanks.

  • 1

    Renan, thank you so much for the explanation above! I managed to understand well how it works. Great Hug.

Browser other questions tagged

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