今天将一个 A list里面的值赋给另外一个B list之后,然后修改A list的值之后,同时把B list的的值也给修改了。
下面是例子:
List<RedLightPerson> redLightPersons = redLightPersonDao.findLast();
for(RedLightPerson redLightPerson : redLightPersons){
redLightPerson.setRun("true");
}
redLightPersonDao.save(redLightPersons);
return new JsonObject(redLightPersons);
返回的list中run的值也变成了true,后面试了各种方法还是不行,后面再高人的指点下用了下面这个方法,问题顺利解决:
List<RedLightPerson> redLightPersons = redLightPersonDao.findLast();
List<RedLightPerson> redLightPersonList = new ArrayList<>();
try {
for (RedLightPerson redLightPerson : redLightPersons) {
redLightPersonList.add((RedLightPerson) BeanUtils.cloneBean(redLightPerson));
redLightPerson.setRun(HAVE_RUN);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
redLightPersonDao.save(redLightPersons);
return new JsonObject(redLightPersonList);
主要是因为上面存到list中的是对象而不是基本类型,所以在修改另外一个列表的值时,也会影响到前面那个列表的对象的值。
而BeanUtils.cloneBean的作用就是复制一个JavaBean的实例。