一开始代码如下,执行后在for循环那一行报错空指针,但是上方已经判断了list不为null,不为空
private List<InstallRow> list;
if (list!= null && !list.isEmpty()) {
for(InstallRow installRow : list) {
if(installRow.getUniqueIndexHashValue().equals(uniqueIndexHashValue)) {
datas.remove(installRow);
}
}
原因是因为list再遍历的过程中被删掉元素导致原先的下一个值找不到
解决方法可以为 删除完毕马上使用break跳出,这样便不会抛出错误
private List<InstallRow> list;
if (list!= null && !list.isEmpty()) {
for(InstallRow installRow : list) {
if(installRow.getUniqueIndexHashValue().equals(uniqueIndexHashValue)) {
datas.remove(installRow);
break;
}
}
但是这种方式只适合删掉某个值,而不是某些值的情况
如果需要删除某些值,就不能使用增强for循环,可以使用iterator遍历
Iterator<String> it = list.iterator();
while(it.hasNext()){
if(installRow.getUniqueIndexHashValue().equals(uniqueIndexHashValue)) {
datas.remove(installRow);
}
}