Chris
Chris

Reputation: 72

ArrayList with empty fileds

I have a problem to handle an Arraylist with empty fields.

As input I have values from an Excel List and there some cells empty (show example).

 Column A  Column B  Column C  Column D 

 Val1      Val2      Val3      Val4 

 Bla1      Bla2      Bla3 

 Hug1      Hug2      Hug3      Hug4 

...

These Values are in an Arraylist so far so good. Now I have a Switch Case where I choose now Column D to work with. The Problem now is that I don’t can handle null fields. These must be removed or get a step over, because my output does not have a null. As I’m trying to do this I got an null pointer exception.

Here is some code:

private Arraylist<ExcelReader> el;

private void doSomething() {

   switch (chooseColumn) {

   // ArrayList is loaded
   //…
   case “D”: 
       // here I want to remove the null fields
       for (int c = 0; c <= el.size(); c++) {
          if(el.get(c).getColumnD().isEmpty()) {
          el.remove(c);
          }
       }
   break;
   // …

}

I’ve tried it at the point where I write it back to a file, but got the null pointer exception. Where is my mistake? What am I doing wrong?

Upvotes: 1

Views: 235

Answers (2)

Jayanand Raghuwanshi
Jayanand Raghuwanshi

Reputation: 499

private Arraylist<ExcelReader> el;

private void doSomething() {

switch (chooseColumn) {

// ArrayList is loaded
//…
case “D”: 
   // here use removeAll to remove all null object
   el.removeAll(Collections.singleton(null));  
   for (int c = 0; c <= el.size(); c++) {
      if(el.get(c).getColumnD().isEmpty()) {
      el.remove(c);
      }
   }
break;
// …

}

Upvotes: 2

R. Mittal
R. Mittal

Reputation: 126

You should understand that isEmpty() does not check on null values. It only checks if size==0 or not. So for checking null values, you should check on condition getColumnD() != null

Upvotes: 1

Related Questions