日期:2014-05-20  浏览次数:20836 次

向list 集中存入bean 总是只能取出最后一个bean的值
           Book book=new Book();    //Book bean
           List<Book> list = new ArrayList<Book>();
   for ( Iterator i = root.elementIterator( "book" ); i.hasNext(); ) {
            Element foo = (Element) i.next();
        
            book.setBookId(foo.attributeValue("bookId"));
            book.setBookName(foo.attributeValue("bookName"));
            Double price =Double.parseDouble(foo.attributeValue("bookPrice"));
            book.setBookPrice(price);
            book.setBookAuthor(foo.attributeValue("bookAuthor"));
            book.setDescription(foo.attributeValue("description"));
            list.add(book);
        
                   }
           return list;
?

------解决方案--------------------
  
           List<Book> list = new ArrayList<Book>();
   for ( Iterator i = root.elementIterator( "book" ); i.hasNext(); ) {
           Book book=new Book();    //Book bean
            Element foo = (Element) i.next();
        
            book.setBookId(foo.attributeValue("bookId"));
            book.setBookName(foo.attributeValue("bookName"));
            Double price =Double.parseDouble(foo.attributeValue("bookPrice"));
            book.setBookPrice(price);
            book.setBookAuthor(foo.attributeValue("bookAuthor"));
            book.setDescription(foo.attributeValue("description"));
            list.add(book);
        
                   }
           return list;
试一下
------解决方案--------------------
你把Book book = new Book()放到循环里面就行了,你相当于是把同一个对象重复放入list