我在使用此代码时遇到了一些麻烦:
ArrayList<Shop> listShops = new ArrayList<Shop>();
Shop currShop = new Shop();
String query = "SELECT * FROM Shop WHERE... ";
try {
PreparedStatement statement = connection.prepareStatement(query);
ResultSet rs = statement.executeQuery();
while(rs.next()) {
currShop.setName(rs.getString(1));
currShop.setDescription(rs.getString(2));
System.out.println(listShops.add(currShop));
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("List size: "+listShop.getSize());
for(Shop s: listShop) {
System.out.println(s.getName());
}
输出:
true
true
true
[...]
List size: 78
[78 empty strings]
而且我不明白为什么它给了我这些空白。我100%确信currShop可以正常工作,因为我打印了
currShop.getName()
和currShop.getDescription()
(同时在rs.next()中)并且它们都可以工作。它还给了我“ true”布尔值,表示已成功插入ArrayList,所以为什么不打印任何内容? 最佳答案
您应该在while循环中每次创建一个新的Shop
对象:
while(rs.next()) {
Shop currShop = new Shop();
currShop.setName(rs.getString(1));
currShop.setDescription(rs.getString(2));
System.out.println(listShops.add(currShop));
}
否则,您只是多次向列表中添加一个
Shop
实例,从而在每次迭代时覆盖名称和描述。