以下是错误的
String name;
List<HotWordsBean> list = new ArrayList<HotWordsBean>();
HotWordsBean hw = new HotWordsBean();
SqlConnect db = new SqlConnect();
if (db.createConnection()) {
String check = "select * from words order by num desc limit 3";
db.query(check);
while (db.next()) {
name = db.getValue("word");
hw.setHotWord(name);
list.add(hw);
}
}
只生成了对象hw,是错误的,应该生成一个数组去赋值,否则list中只加入了最后 一个。
也不知道为什么。以下是正确的,可以正常输出
public static void main(String[] args) {
String name[]=new String[3];
List<HotWordsBean> list = new ArrayList<HotWordsBean>();
HotWordsBean hw[] = new HotWordsBean[3];
int i=0;
SqlConnect db = new SqlConnect();
if (db.createConnection()) {
String check = "select * from words order by num desc limit 3";
db.query(check);
while (db.next()) {
name[i] = db.getValue("word");
i++;
}
}
for(int j=0;j<name.length;j++){
hw[j]=new HotWordsBean();
System.out.println("name "+name[j]);
hw[j].setHotWord(name[j]);
System.out.println("HW "+hw[j].getHotWord());
list.add(hw[j]);
}
System.out.println(list.size());
for (int i1 = 0; i1 < list.size(); i1++) {
hw[i1]=list.get(i1);
System.out.println("list: "+hw[i1].getHotWord());
}
}