lifelinger

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  1 Posts :: 0 Stories :: 2 Comments :: 0 Trackbacks
今天差点被一段代码给陷阱了。
1 List<BidDO> bidDOs=result.getBids();
2 List<AuctionBid> abids = new ArrayList<AuctionBid>();
3 AuctionBid abid = new AuctionBid();
4 for(BidDO bid : bidDOs){
5   abid = this.translate(bid);//把bidDO转成AuctionBid
6   abids.add(abid);
7 }
8 
debug的时候才发现abids里面的值都是同一个,而且是最后add进去的那个abid值。原来是我add进去的abid都是对同一个对象的引用,每次重新赋值都会把原有的值给覆盖掉了,才导致错误的结果。
这个问题其实是挺简单的,就是没有注意变量的作用域.因为abid变量的作用域是全局的,是对对象AuctionBid的一个引用,所以在for循环中对abid的不同赋值,其实都是对AuctionBid对象产生了影响,因为你使用的是同一个引用(指针)。
解决的话把AuctionBid abid = new AuctionBid()这句在for循环中声明即可。
posted on 2010-03-22 22:12 whicky 阅读(83) 评论(2)  编辑  收藏

Feedback

# re: 陷阱--作用域范围 2010-03-22 23:31 xylz
List<Integer> list = new ArrayList<Integer>();
Integer v=new Integer(0);
for(int i=0;i<10;i++) {
v=new Integer(i);
list.add(v);
}
for(Integer x:list)
System.out.println(x);

Run:
0
1
2
3
4
5
6
7
8
9
  回复  更多评论
  

# re: 陷阱--作用域范围 2010-03-23 10:08 whicky
@xylz
Integer v=new Integer(0);
v=new Integer(i);
这个不是一样的么?  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: