-2

I have a list with 20 elements, but it contains a null value at the 15 position, how can I remove the null value from an List?

diogojme
  • 2,309
  • 1
  • 19
  • 25

3 Answers3

1

If you don't want the 'null' image to appear on a list, just do something like:

for each item on a list
    if item == null then continue
    else 
        add an item to <List>Images

If you pass a null object to the List of Images, it still does occupy the place in the list, even though this place is technically uninitialized.

PurrgnarMeowbro
  • 338
  • 5
  • 14
1

you can't say null value means the object is not exist, even null isn't an object in java.

String s = null means the reference of String s is unset, but the declare is done, an object with String type and called s.

see more detail about it, oracle doc: The Kinds of Types and Values

public static void main(String[] args)
{
    ArrayList al = new ArrayList();
    al.add(null);
    al.add("not null");
    System.out.println(al.size()); //output 2

    //if you wanna know how many objects inside of list and isn't null
    int count=0;
    for(Object obj:al)
        if(!(obj==null)) 
            count++;
    System.out.println(count); //output 1

    System.out.println(al); //output [null, not null] ← null is exist.
}

so in you case, the return of size() should be 20.

TomN
  • 574
  • 3
  • 18
1

I use the solution from @Lithium after some days researching

tourists.removeAll(Collections.singleton(null));

This code remove all null values from an list.

Community
  • 1
  • 1
diogojme
  • 2,309
  • 1
  • 19
  • 25