1

I have an arrayList called Arr_SxCorrel_table2d like: The ArrayList is of the type: ArrayList<List<String>>

Arr_SxCorrel_table2dREMOVAL[[OF, RE, RE, RE, IND], [HA, 22, 3, 1, 4, 18%], [HA, 7, 3, 1, 4, 57%], [REG, 3, 1, 0, 1, 33%], [BING, 4, 3, 33, 32, 23%], [], [NOTE: details.], [], [], []]

I want to get rid of the elements that are empty. I tried:

for (int i=0;i<Arr_SxCorrel_table2d.size(); i++) {
                 if (Arr_SxCorrel_table2d.get(i) == null){
                     Arr_SxCorrel_table2d.remove(i); 
                         }
                 }

But nothing gets removed. Not sure what the next step should be

6
  • There are no null elements in your lists. Commented Apr 26, 2016 at 6:53
  • So what are these []. Do they contain whitespace?? Commented Apr 26, 2016 at 6:56
  • They can either be empty lists, or lists containing a single whitespace element. But you're obviously in a much better position to find out. Commented Apr 26, 2016 at 6:57
  • Could it contain a carriage return element. Is that possible so it would look as i does? Commented Apr 26, 2016 at 7:07
  • try also to check for the size of the ArrayList. Commented Apr 26, 2016 at 7:08

2 Answers 2

2

Your code removes null references from the outer List, it doesn't remove empty Lists.

Try :

for (int i=0;i<Arr_SxCorrel_table2d.size(); i++) {
    if (Arr_SxCorrel_table2d.get(i) == null || Arr_SxCorrel_table2d.get(i).isEmpty()){
        Arr_SxCorrel_table2d.remove(i); 
        i--;
    }
}

Note that i must be decremented whenever you remove an element from the List, since the indices of the elements that follow the removed element are decremented.

Sign up to request clarification or add additional context in comments.

2 Comments

OK but the elements are still not removed.
@SebastianZeki If the [] elements in the question represent empty inner Lists, they should be caught by the Arr_SxCorrel_table2d.get(i).isEmpty() condition and removed.
0

You can check their size if they are more than 0 :

for (int i = 0; i < Arr_SxCorrel_table2d.size(); i++) {
    if (Arr_SxCorrel_table2d.get(i).size() == 0) {
        Arr_SxCorrel_table2d.remove(i--);
    }
}

There's no need to check if there is a null value because it will not compile if the variable is given a null value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.