今天差點(diǎn)被一段代碼給陷阱了。
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轉(zhuǎn)成AuctionBid
6 abids.add(abid);
7 }
8
debug的時(shí)候才發(fā)現(xiàn)abids里面的值都是同一個(gè),而且是最后add進(jìn)去的那個(gè)abid值。原來是我add進(jìn)去的abid都是對(duì)同一個(gè)對(duì)象的引用,每次重新賦值都會(huì)把原有的值給覆蓋掉了,才導(dǎo)致錯(cuò)誤的結(jié)果。
這個(gè)問題其實(shí)是挺簡(jiǎn)單的,就是沒有注意變量的作用域.因?yàn)閍bid變量的作用域是全局的,是對(duì)對(duì)象AuctionBid的一個(gè)引用,所以在for循環(huán)中對(duì)abid的不同賦值,其實(shí)都是對(duì)AuctionBid對(duì)象產(chǎn)生了影響,因?yàn)槟闶褂玫氖峭粋€(gè)引用(指針)。
解決的話把AuctionBid abid = new AuctionBid()這句在for循環(huán)中聲明即可。