Java null element in ArrayList array

I just had a simple question that Google cannot solve. So, if I set some of the elements ArrayListequal null, will they still be counted in list.size()and will the indices of the remaining elements be kept?

If not, can any of you advise how I can do this?

+3
source share
5 answers

Yes, look at the implementation of the method add(), for example:

public boolean add(E object) {
    Object[] a = array;
    int s = size;
    if (s == a.length) {
        Object[] newArray = new Object[s +
                (s < (MIN_CAPACITY_INCREMENT / 2) ?
                 MIN_CAPACITY_INCREMENT : s >> 1)];
        System.arraycopy(a, 0, newArray, 0, s);
        array = a = newArray;
    }
    a[s] = object;
    size = s + 1;
    modCount++;
    return true;
}

Since it ArrayList.size()returns only the value of the variable size, it is clear that if you add null, the size will be increased by 1, so yes, it nullcounts.

+5
source

Yes and yes, you can verify this with this simple code.

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        list.add("" + i);
    }
    System.out.println(list.size() + " " + list);
    list.set(0, null);
    System.out.println(list.size() + " " + list);
}

10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10 [null, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+2

, - , .

+1

MyList.removeAll(Collections.singleton(null));
MyList.size();

: http://www.mhaller.de/archives/12-How-to-remove-all-null-elements-from-a-Collection.html

0

, , ArrayList , ArrayList .

List ArrayList, :

:

( ).... , . , , .

ArrayList:

Implementation of a variable array of the List interface. Implements all optional operations with a list and resolves all elements, including zero.

The contract says that ArrayList allows null elements, so the answer to your question is yes, the size of the list and indexes remain unchanged.

0
source

All Articles