日期:2014-05-20  浏览次数:20685 次

关于ArrayList集合的问题
public List<News> searchNews() {
try {
this.setPs(getConn().prepareStatement("select * from News"));
this.setRs(this.getPs().executeQuery());
List<News> list=new ArrayList<News>();
while(getRs().next())
{
News n = new News();
n.setId(getRs().getInt(1));
n.setTitle(getRs().getString(2));
n.setAuthor(getRs().getString(3));
n.setTime(getRs().getDate(4).toString());
n.setBody(getRs().getString(5));
list.add(n);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally
{
closeAll(getConn(), getPs(), getRs());
}
我把数据库结果集存入到News实体类中,再把News存入ArrayList集合中,
怎么从list集合中读取每条信息。
为什么我只能读取一条信息。

------解决方案--------------------
for (News news : list) {
news.getId(); news.getAuthor();
}
------解决方案--------------------
除了1楼所说的遍历方法,也可以这样遍历:

Java code

String author;
int id;
for (int i=0; i<list.size; i++) {
  id = list.get(i).getId();
  author = list.get(i).getAuthor();
  //......
}

------解决方案--------------------
一楼正解.
int id=0;
String author;
if(list != null){
for(News news : list){
id = news.getId();
author = news.getAuthor();
}
}