在写一个项目时,需要用到ECharts图表,需要从后台传一个List集合给前端,List集合存储的是一个对象类型,在前端接受到数据,发现List集合里面的数据都是一样,后面排查发现是new对象放在了循环外面,把new放在,循环里面就行了
下面是一段错误代码:
List结果:
[ShopPieChert(name=白菜, value=8.0, count=null, goodsId=2), ShopPieChert(name=白菜, value=8.0, count=null, goodsId=2), ShopPieChert(name=白菜, value=8.0, count=null, goodsId=2)]
改正:
List结果:
[ShopPieChert(name=苹果, value=18.0, count=null, goodsId=1), ShopPieChert(name=梨子, value=12.0, count=null, goodsId=3), ShopPieChert(name=白菜, value=8.0, count=null, goodsId=2)]
原因:我们只需要把new对象的时候放入循环里面,因为List里面存储对象时,只是存储了其地址,开始把new放在外面,我们List里存的都是一个对象的引用地址,所以List里面的值一样,
现在把new对象放在循环里面,List里面就是存储的不同的对象的引用地址了