错误1:Bean中的属性设置为static,导致new出来的所有Bean的属性都为最后一次new出来的Bean的属性。
处理方法:把Bean中属性的static去掉就ok了。
错误2:循环添加元素到List<E> list 中的时候,所添加的元素为E e 对象,要保证这些对象不为同一个对象,也就是说,每次添加的元素都是一个新new出来的对象,实例如下:
代码段1:
public static void getCategories(List<Category> list, int id) {
Connection conn = DB.getConn();
String sql = "select * from category where pid = " + id + ";";
ResultSet rs = DB.executeQuery(sql, conn);
try {
while(rs.next()) {
Category cate = new Category();
cate.setId(rs.getInt("id"));
cate.setName(rs.getString("name"));
//System.out.println(rs.getString("name"));
cate.setDescr(rs.getString("descr"));
cate.setPid(rs.getInt("pid"));
cate.setLeaf((rs.getInt("isleaf") == 0) ? true : false);
cate.setGrade(rs.getInt("grade"));
list.add(cate);
if(!cate.isLeaf()) {
getCategories(list, cate.getId());
}
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DB.closeRs(rs);
DB.closeConn(conn);
}
}
代码段2:
public static void getCategories(List<Category> list, int id) {
Connection conn = DB.getConn();
String sql = "select * from category where pid = " + id + ";";
ResultSet rs = DB.executeQuery(sql, conn);
<pre name="code" class="java"> Category cate = new Category();
try {while(rs.next()) {cate.setId(rs.getInt("id"));cate.setName(rs.getString("name"));//System.out.println(rs.getString("name"));cate.setDescr(rs.getString("descr"));cate.setPid(rs.getInt("pid"));cate.setLeaf((rs.getInt("isleaf") == 0) ? true : false);cate.setGrade(rs.getInt("grade"));list.add(cate);if(!cate.isLeaf()) {getCategories(list, cate.getId());}}} catch (SQLException e) {e.printStackTrace();}finally {DB.closeRs(rs);DB.closeConn(conn);}}
比较以上两段代码,代码段1为正确的,2为错误的。1中 Category cate = new Category(); 是在while循环中写的,每次循环都会new一个Category对象,所以添加到list中的元素都是不同的对象,不会出现元素覆盖的情况。
代码段2中就不同了,Category cate = new Category(); 是在循环外写的,每次循环添加到list中的元素都是同一个对象,只不过是每次循环的时候把cate的属性改变了,到最后一次循环结束这个对象cate的属性就为最后那次循环的了,因此,list中所有的元素都是cate了。