public List<DemandDTO> findAll() {Iterator<Demand> demands=demandDAO.findAll().iterator();demanddtos=new ArrayList<DemandDTO>();demanddto=new DemandDTO();while(demands.hasNext()){Demand demand=demands.next();demanddto.setPkDemandId(demand.getPkDemandId());demanddto.setPkDeptId(demand.getDept().getPkDeptId());demanddto.setDeptName(demand.getDept().getDeptName());demanddto.setDeptLeader(demand.getDept().getDeptLeader());demanddto.setDemandFrom(demand.getDemandFrom());demanddto.setDemandMan(demand.getDemandMan());demanddto.setDemandName(demand.getDemandName());demanddto.setDemandCount(demand.getDemandCount());demanddto.setFitResumeNum(fitResumeNum(demand.getPkDemandId()));demanddto.setSendResumeNum(sendResumeNum());demanddto.setJoinInterviewNum(joinInterviewNum());demanddto.setThroughInterviewNum(throughInterviewNum());demanddto.setStartTime(demand.getStartTime());demanddto.setEndTime(demand.getEndTime());demanddto.setDemandState(demand.getDemandState());demanddto.setDemandDes(demand.getDemandDes());demanddtos.add(demanddto);}return demanddtos;}在循环体内用system.out.println(demanddtos.get(0).getDemandName)输出的结果是正确的,可以输出demanddtos里面的添加的DemandName,也就是说,都添加到0这个位置了,这是为什么啊?
4 回答
![?](http://img1.sycdn.imooc.com/533e4ce900010ae802000200-100-100.jpg)
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
自始至终,demanddto只new了一个对象,无论demands循环了多少次,始终用了demanddto这一个对象,那个demanddtos.add(demanddto);这一句其实加的都是同一个对象,那么当然里面始终只有一个对象了。你应该这样:
while(demands.hasNext())
{
Demand demand=demands.next();
demanddto=new DemandDTO();
...
demanddtos.add(demanddto);
}
return demanddtos;
这样,每循环一次都new了一个对象,Arraylist才会不断把新对象加到末尾
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
demanddto=new DemandDTO();
while(demands.hasNext())
{
调整为
while(demands.hasNext())
{
demanddto=new DemandDTO();
你在外面new, 由于地址永远不变,所以添加的始终是最后一个元素的内容
![?](http://img1.sycdn.imooc.com/5333a2320001acdd02000200-100-100.jpg)
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
在Demand demand=demands.next();下面加一句demanddto=new DemandDTO();,你现在这样每次循环往list里里面放的都是同一个demanddto对象,只不过每次都重新给它的属性重新赋值了而已。
添加回答
举报
0/150
提交
取消