public Collection getDepartments(){
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        Collection departments = new ArrayList();
    try{
            con = ConnectionFactory.getConnection();
            st = con.createStatement();
            String sql = "select * from dept";
            rs = st.executeQuery(sql);
            //Department dept = new Department();1--对象创建在while循环体外,查询结果重复显示最后一条记录???
            while(rs.next()){
                Department dept = new Department();//2--对象创建在while循环体内,正常显示查询结果
                dept.setDeptno(rs.getInt("deptno"));
                dept.setDname(rs.getString("dname"));
                dept.setLoc(rs.getString("loc"));
                departments.add(dept);
            }
            //return departments;

解决方案 »

  1.   

    1--情况下,错误显示如下所示:
    部门编号 部门名称 所在区域 
    40 OPERATIONS BOSTON 
    40 OPERATIONS BOSTON 
    40 OPERATIONS BOSTON 
    40 OPERATIONS BOSTON 2--正常显示情况如下所示:
    部门编号 部门名称 所在区域 
    10 ACCOUNTING NEW YORK 
    20 RESEARCH DALLAS 
    30 SALES CHICAGO 
    40 OPERATIONS BOSTON 
      

  2.   

    好熟悉的问题,06年,我手下一个新毕业学生也犯过类似的迷糊。
    Department dept = new Department();//1对象创建在while循环体外,查询结果重复显示最后一条记录??? 
    //这种方式,dept永远只有一个,循环每次赋值,都是在同一个对象上(覆盖前次的值),
    //因此,最后你得到的个数是对的,但都是同样的值(实际上,整个departments都引用了同一个对象dept)
                while(rs.next()){ 
                    dept.setDeptno(rs.getInt("deptno")); 
                    dept.setDname(rs.getString("dname")); 
                    dept.setLoc(rs.getString("loc")); 
                    departments.add(dept); 
                } 
                while(rs.next()){ 
                    Department dept = new Department();//2--对象创建在while循环体内,正常显示查询结果 
    //这种方式,每次都创建新的对象,所以能够每个对象上保存不同的值(而上一个对象已经被加入到departments中了)
                    dept.setDeptno(rs.getInt("deptno")); 
                    dept.setDname(rs.getString("dname")); 
                    dept.setLoc(rs.getString("loc")); 
                    departments.add(dept); 
                } 所以,这不是变量作用范围的问题,而是对“对象引用”的理解有问题。
      

  3.   

    写在循环外的话, 
    list里的4个元素都指向了同一个dept的引用
    -------------
    第一遍循环,dpet是编号为10的对象,这个时候把dept  add到list
    第二遍,dept.setDeptno(20)的时候,这个dept和上一次循环其实是相同的引用,这个时候,第一次循环加进去的dept其实被改成了20
    。。以此类推
    第4遍 set(40)以后,所有的这4个元素其实都是同一个引用,所以都是最后那次设置的值