Doubt on List that does not return the result

6

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

The method is querying the DB 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;
}

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

    
asked by anonymous 15.11.2016 / 01:44

2 answers

8

You should override the toString() of class alunos . For example:

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

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

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

Also, I suggest renaming the class to Aluno instead of alunos . The reason for this is that the default for class names is to use nouns in the singular and beginning with a capital letter.

    
15.11.2016 / 01:47
6

Since @VictorStafusa suggested, overwriting the toString() method is one of the ways, and in addition to other great observations regarding the code presented.

But for overriding, I particularly do not like to override this method, unless it's something really justifiable.

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

ArrayList<alunos> listaAlunos = teste();

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

Based on the assumption that, in addition to the setters, you also created getters for the properties of the student class.

    
15.11.2016 / 01:55