在迭代器循环中更新列表

Update a list inside iterator loop

此代码尝试遍历 excel 文件并将数据加载到 List<List<String>> 但它在 resultList.add(rrow) 处抛出 java.lang.NullPointerException 但不清楚是什么它的问题:

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class ReadExcel {
        public List<List<String>> resultList;
    
        public List<List<String>> ReadExcelToList(String csvPath) throws IOException {
            try {
    
                FileInputStream excelFile = new FileInputStream(csvPath);
                Workbook workbook = new XSSFWorkbook(excelFile);
                System.out.println(workbook.getSheetName(0));
                Sheet datatypeSheet = workbook.getSheetAt(0);
                Iterator<Row> iterator = datatypeSheet.iterator();
                while (iterator.hasNext()) {
    
                    Row currentRow = iterator.next();
                    Iterator<Cell> cellIterator = currentRow.iterator();
                    List<String> rrow = new ArrayList<>();
                    while (cellIterator.hasNext()) {
    
                        Cell currentCell = cellIterator.next();
                        switch (currentCell.getCellType()) {
                            case Cell.CELL_TYPE_STRING:
                                rrow.add(currentCell.getStringCellValue());
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                           rrow.add(String.valueOf(currentCell.getNumericCellValue()));
                             break;
                        }
                    }
                    resultList.add(rrow);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultList;
        }
    }

java.lang.NullPointerException
    at ReadExcel.readExcelToList(ReadExcel.java:40)
    at BasicCSVReader.main(BasicCSVReader.java:35)

您的 resultList 从未创建(它是 null)。您可以通过如下定义来修复它:

public List<List<String>> resultList = new ArrayList<>();