Doubt about List that does not return the result

Asked

Viewed 99 times

6

I have this method in Java, which queries in the database and returns me a list of students.

The method is searching in the BD, but does not return the data correctly...

public static List<alunos> teste() throws SQLException {

    String sql = "Select * from alunos";
    Statement stm = Conectar.Mysql(ip(), banco(), usuario(), senha(), sql);
    ResultSet rs = stm.executeQuery(sql);
    List<alunos> valores = new ArrayList<>();
    while (rs.next()) {
        alunos objeto = new alunos();
        objeto.setNome(rs.getString("nome"));
        objeto.setMatricula(rs.getString("matricula"));
        objeto.setCurso(rs.getString("curso"));
        valores.add(objeto);
    }

    return valores;
}

He returns to me [teste.alunos@e26948, teste.alunos@1baeedf, teste.alunos@3f4d3d, teste.alunos@13b32d7]

  • Why not make a loop to display each Arraylist item?

2 answers

8


You must override the method toString() class alunos. For example:

@Override
public String toString() {
    return nome + " (" + matricula + ") - " + curso;
}

The method toString is the method responsible for giving a representation in the format of String for some object.

The default implementation that is inherited from the class Object is not very useful, and it is the one you are getting, which returns the class name, followed by an arroba and a hexadecimal hash code. Since standard implementation should not serve, it should be overwritten with a better.

Also, I suggest changing the class name to Aluno instead of alunos. The reason for this is that the default for class names is to use singular nouns and starting with uppercase letters.

  • Victor, thank you very much solved my problem

  • @Junior If my answer has served you, could you please mark it as accepted/correct by clicking on the green symbol next to it? Thank you.

6

As @Victorstafusa suggested, overwrite the method toString() is one of the ways, and in addition to other great observations regarding the code presented.

But regarding the superscript, I don’t particularly like to overwrite that method, unless it’s for something really justifiable.

If the method returns a ArrayList, just go through with a loop to display the information:

ArrayList<alunos> listaAlunos = teste();

for(alunos a: listaAlunos){
   System.out.prinln("Nome: " + a.getNome() + 
     " - Matricula: " + a.getMatricula() + 
     " - Curso: " + a.getCurso());
}

Assuming that, in addition to setters, you also created getters for student class properties.

Browser other questions tagged

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