How to present data in the ArrayList in Java [duplicate]

0

How do I sort information stored in an ArrayList in java? Follow the code for review.

public class Main {
    public static void main(String[] args) {
        Aluno aluno = new Aluno();
        ArrayList<Aluno> array_aluno = new ArrayList<Aluno>();
        for (int cont = 1; cont <= 3; cont++){
            aluno.setNome(JOptionPane.showInputDialog("Insira o nome do aluno: ") );
            aluno.setTelefone(JOptionPane.showInputDialog("Insira o telefone do aluno: ") );
            array_aluno.add(aluno);
        }

        for (int cont = 0; cont <= array_aluno.size() ; cont++){
            System.out.println(array_aluno.get(cont) );
        }
    }   
}
    
asked by anonymous 22.02.2018 / 18:37

1 answer

2

In class Aluno you can override toString() :

@Override
 public String toString() {
      return ("Nome:"+this.getNome() + " Telefone: "+ this.getTelefone());
 }

And use this structure in main :

public class Main {
    public static void main(String[] args) {
        ArrayList<Aluno> array_aluno = new ArrayList<Aluno>();
        for (int cont = 1; cont <= 3; cont++){
            Aluno aluno = new Aluno();
            aluno.setNome(JOptionPane.showInputDialog("Insira o nome do aluno: ") );
            aluno.setTelefone(JOptionPane.showInputDialog("Insira o telefone do aluno: ") );
            array_aluno.add(aluno);
        }

        System.out.println(array_aluno);
    }   
}

After commenting on Articundo , I moved the creation of Aluno to within for (the object was always being overwritten.)

    
22.02.2018 / 18:44