我有一个生成并返回ArrayList的方法。如何从其他类打印ArrayList?
public ArrayList<Printer> selectAllePrinters() {
ArrayList<Printer> printers = new ArrayList<>();
try {
Connection con = SimpleDataSource.getConnection();
PreparedStatement stat = con.prepareStatement("SELECT * FROM printer;");
ResultSet result = stat.executeQuery();
while (result.next()) {
Printer printer = new Printer();
printer.setPrinterid(result.getString("printerid"));
printer.setNaam(result.getString("printernaam"));
printer.setAantalKl(result.getInt("aantalkleur"));
printer.setAantalZw(result.getInt("aantalzwart"));
}
result.close();
stat.close();
return printers;
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
提前致谢!
答案 0 :(得分:0)
在您的方法中,将新打印机添加到arraylist。
while (result.next()) {
Printer printer = new Printer();
printer.setPrinterid(result.getString("printerid"));
printer.setNaam(result.getString("printernaam"));
printer.setAantalKl(result.getInt("aantalkleur"));
printer.setAantalZw(result.getInt("aantalzwart"));
printers.add(printer); // Adds the printer to the arraylist.
}
然后打印出来。
System.out.println(selectAllePrinters());