2

I am trying to delete empty cell in apache-poi. I get this error at unmarkedColumns.remove(unmarkedColumns.get(i)): There is a problem with remove method. I don't understand why.Can you help me?

java.lang.UnsupportedOperationException: null
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
)    
 Integer[] integers = new Integer[headers.size()];
    Arrays.fill(integers, 0);
    List<Integer> unmarkedColumns = Arrays.asList(integers);
    for (ScoredFormData scoredFormData : scoredFormDatas) {
        Row dataRow = sheet.createRow(++rownum);
        List<Object> rowValues = prepareExportRow(scoredFormData, visitManager, parameters, 
     dynamicDatamanager,
                scoreCriteriaDefinitions);
        for (int i = 0; i < rowValues.size(); i++) {
            if (unmarkedColumns.get(i) != 1 && rowValues.get(i) != null
                    && !rowValues.get(i).equals("")) {
                unmarkedColumns.set(i, 1); 
            }
        }
        populateCells(rowValues, dataRow);
    }

    for (int i = 0; i < unmarkedColumns.size(); i++) {
        if (unmarkedColumns.get(i) == 0) {
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Boolean changed = false;
                for (int j = i + 1; j < row.getLastCellNum() + 1; j++) {
                    Cell oldCell = row.getCell(j - 1);
                    if (oldCell != null) {
                        row.removeCell(oldCell);
                        changed = true;
                        Cell nextCell = row.getCell(j);
                        if (nextCell != null) {
                            Cell newCell = row.createCell(j - 1, nextCell.getCellType());
                            switch (newCell.getCellType()) {
                            case Cell.CELL_TYPE_BOOLEAN: {
                                newCell.setCellValue(nextCell.getBooleanCellValue());
                                break;}}}}


                if (changed ) {
                    unmarkedColumns.remove(unmarkedColumns.get(i));
                    i = 0;
                }
            }
user9413194
  • 119
  • 2
  • 3
  • 9

2 Answers2

6

Arrays.asList(..) returns a List with a fixed size, so you can't expand or shrink it.

To fix it, you could wrap it in an ArrayList:

List<Integer> unmarkedColumns = new ArrayList<>(Arrays.asList(integers));

Niby
  • 474
  • 1
  • 6
  • 20
1

Your problem is here

List<Integer> unmarkedColumns = Arrays.asList(integers);

If you use Arrays.asList(...), it returns a fixed size list, therefore you cannot remove elements from it.

You could make a workaround by wrapping it:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(integers));
Villat
  • 1,455
  • 1
  • 16
  • 33