Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java null element in ArrayList

Tags:

java

arraylist

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?

like image 517
user2904796 Avatar asked Feb 24 '14 19:02

user2904796


3 Answers

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.

like image 154
nikis Avatar answered Oct 07 '22 10:10

nikis


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

like image 25
Benjamin RD Avatar answered Oct 07 '22 10:10

Benjamin RD


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]
like image 29
endriu_l Avatar answered Oct 07 '22 09:10

endriu_l