1

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?

Draken
  • 3,134
  • 13
  • 34
  • 54
Chris
  • 72
  • 1
  • 8
  • Of course `el.get(c).getColumnD().isEmpty())` will be a problem if you have `null` values. You could check there if you `get(c)` return `null`. – AxelH May 15 '17 at 10:18
  • 1
    Possible duplicate of [How to remove all null elements from a ArrayList or String Array?](http://stackoverflow.com/questions/4819635/how-to-remove-all-null-elements-from-a-arraylist-or-string-array) – AxelH May 15 '17 at 10:19
  • yes value is null – Chris May 15 '17 at 10:23
  • if `el.get(c)` is the one return null, you can see the duplicate to find really nice solutions. If not, this will require some improvments or a condition to filter those without removing it of the list – AxelH May 15 '17 at 10:27

2 Answers2

2
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;
// …

}
1

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

R. Mittal
  • 126
  • 5
  • I've got to null fields in a row, the first one will be removed the second is showing up – Chris May 15 '17 at 11:09