Error printing Array List in Java

Asked

Viewed 134 times

0

I am making a code where is created an Arraylist class "Employee"

public static void main(String[] args) {
    
    int qntFuncionarios;
    
    Scanner sc = new Scanner (System.in);
    List <Empregado> list = new ArrayList<Empregado>();
    

    System.out.println("Favor informar a quantidade de funcionarios que queira cadastrar: ");
    qntFuncionarios = sc.nextInt();
    

    
    for (int i=0; i<qntFuncionarios;i++)
    {
        Empregado empregado = new Empregado();
        System.out.println("Informar o id do funcionario: ");
        empregado.id = sc.nextInt(); 
        System.out.println("\n Informar o nome do funcionário: ");
        empregado.nome = sc.next();
        System.out.println("\n Informar o salario do usuário: ");
        empregado.salario = sc.nextDouble();
        list.add(new Empregado());
    
    }
    
    for (Empregado x : list)
    {
        System.out.println(x);
    }
    
    
}

}

However, when I print through for each, I get that output pattern

"classist.Employee@7d4991ad"

by what I’ve been researching, has something to do with the method toString, but I haven’t found a solution yet.

2 answers

0

for (Empregado x : list)
{
    System.out.println(x);
}

In your code you are giving a System.out.println on the whole object, if I am not mistaken it will return the object hashcode, to return the attributes do equal in the example below:

 for (Empregado x : list)
 {
        System.out.println(x.id);
 System.out.println(x.nome);
    }
  • I actually got out of this hashcode, but I came across another problem, it seems that the information entered, ID, name and salary are not within the list,

  • @Opufpaulistano It’s because you’re doing list.add(new Empregado()), ie, is added a new Empregado (and with the data not filled in). Instead, you should add what already had the data filled in: list.add(empregado)

0

You can solve your problem in two ways, in the first of which you can overwrite the method toString of the employed class, this allows you to keep the code snippet presented in its current state, the process takes place as follows:

public class Empregado {

   @Override
   public String toString() {
          return nome;
   }

}

The second way is you call the method of access to the employee’s name at the time of "printa it", for such, do as follows:

list.forEach(empregado -> {
        System.out.println(empregado.getNome());
});

Browser other questions tagged

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