创建对象在while循环里面和外面的不同效果
1.在while循环的外面
public List<CollectionBean> list() {String sql = "select * from collectiontbl";Connection conn = JDBC_Connection.getConnection();Statement stmt = null;ResultSet rs = null;List<CollectionBean> list = new ArrayList<CollectionBean>();try {stmt = conn.createStatement();rs = stmt.executeQuery(sql);CollectionBean bean = new CollectionBean();while (rs.next()) {//不能再while外面创建这个对象,这是一个非常有技术含量的问题 bean.setId(rs.getInt("id"));bean.setName(rs.getString("name"));bean.setName(rs.getString("url"));list.add(bean);}for(int i=0;i<list.size();i++){System.out.println(list.get(i).getId()+" "+list.get(i).getName());}return list;} catch (SQLException e) {e.printStackTrace();} finally {JDBC_Connection.free(rs, conn, stmt);}return null;}运行结果:1 www.dkfj.com2 www.dkfj.com3 www.dkfj.com4 www.dkfj.com5 www.dkfj.com6 www.dkfj.com原因解释:
我们注意到这个结果显然不是我们想要的,因为创建了一个对象在while循环外面,每循环一次创建的对象都没有变,改变的只是在栈上的值,而添加到list里的对象都指向到还存在的这个对象的栈上。当最后对象消失的时候,list里所有的对象才把栈上的值copy起走,所以打印的结果全部是一样的。所以我们需要把创建对象放在while循环内。
下面是详细的图解:

1.在while循环的里面
public List<CollectionBean> list() {String sql = "select * from collectiontbl";Connection conn = JDBC_Connection.getConnection();Statement stmt = null;ResultSet rs = null;List<CollectionBean> list = new ArrayList<CollectionBean>();try {stmt = conn.createStatement();rs = stmt.executeQuery(sql);while (rs.next()) {//不能再while外面创建这个对象,这是一个非常有技术含量的问题 CollectionBean bean = new CollectionBean();bean.setId(rs.getInt("id"));bean.setName(rs.getString("name"));bean.setName(rs.getString("url"));list.add(bean);}for(int i=0;i<list.size();i++){System.out.println(list.get(i).getId()+" "+list.get(i).getName());}return list;} catch (SQLException e) {e.printStackTrace();} finally {JDBC_Connection.free(rs, conn, stmt);}return null;}运行结果:1 www.baidu.com2 www.google.com3 www.google.com4 www.javaeye5 www.javaeye6 www.dkfj.com原因解释: