Null pointer access: The variable marketcommends can only be null at this location


Null pointer access: The variable marketcommends can only be null at this location


源代码:

List meunList=backServiceInter.getmeunBypage(9,1);
		List meunrealList=new ArrayList();
		Meun meun=null;
		Photo photo=null;
		List<Marketmeun> marketlist=new ArrayList<Marketmeun>();
		marketlist=null;
		List<Market> marketcommends=new ArrayList<Market>();
		Market market=null;
		Marketmeun marketmeun=null;
		MeunQueryVo meunQueryVo=new MeunQueryVo();
		for(int i=0;i<meunList.size();i++)
		{
			meun=(Meun)meunList.get(i);
			photo=(Photo)backServiceInter.getPhoto("2",meun.getId());
			marketlist=backServiceInter.getMarketmeun(meun.getId());
			marketcommends.clear();
			/*错误的写法*/  
			//marketcommends=null;
			for(int j=0;j<marketlist.size();j++)
			{
				marketmeun=(Marketmeun)marketlist.get(j);
				market=(Market)backServiceInter.findById(Market.class,marketmeun.getMarket().getId());
				marketcommends.add(j,market);
				System.out.println("market="+market.getName());
			}
			meunQueryVo.setCommendmarkets(marketcommends);
			//System.out.println("marketcommends="+marketcommends.size());
			meunQueryVo.setMeun(meun);
			meunQueryVo.setBigImage(photo.getBigphoto());
			meunrealList.add(i,meunQueryVo);
		}


在一般的for循环时,为了避免过多的new 对象,常常采用上面的写法,即把对象先在对象外创建好,然后=null,但是List要注意, 
 
marketcommends=null
意味着把数组置空,下面的
marketcommends.add(j,market);
自然加不进去了,List会默认为空,如果要在每次for循环前清空List,用clear() 即可。


你可能感兴趣的:(list,null,nullPointer)