JAVA中使用增強for循環刪除list中某元素報錯空指針

一開始代碼如下,執行後在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);
   }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章