list add对象踩的坑

list 添加对象时,没有把new object写到循环体里,导致最后添加了相同的一个对象;

public List<goods> find(String goodsname) {
		List<goods>list = new ArrayList<goods>() ;
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from goods where goods_name=?";
		try {
			int i=0;
			pstmt = (PreparedStatement) c.prepareStatement(sql);
			pstmt.setString(1, goodsname);
			rs = (ResultSet) pstmt.executeQuery();
			while (rs.next()) {
				goods = new goods();
				goods.setGoods_id(rs.getString(1));
				goods.setGoods_name(rs.getString(2));
				goods.setGoods_sum(rs.getString(3));
				goods.setGoods_price(rs.getString(4));
				goods.setGoods_from(rs.getString(5));
				goods.setGoods_time(rs.getString(6));
			
				list.add(i++, goods);
						 
			}
		 
			
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
其中 goods = new goods();一定要放到循环体里面。
posted @ 2018-12-10 19:12  zhaocundang  阅读(1008)  评论(0编辑  收藏  举报