I just had a simple question that google is being unable to resolve. So if I set some of the elements of an ArrayList are set to null, will they still be counted in list.size(), and will the indices for the remaining elements still remain intact?
If not, can any of you advise as to how I can do that?
Yes, take a look on a add() method implementation, 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 ArrayList.size() returns just the value of size variable, it's clear, that if you add null, the size will be increased by 1, so, yes, null is counted.
You can remove all the elements from your list
MyList.removeAll(Collections.singleton(null));
MyList.size();
Reference: http://www.mhaller.de/archives/12-How-to-remove-all-null-elements-from-a-Collection.html
Yes and Yes, you can verify it 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]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With