Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java inserts null to array when using List.toArray

The output of the code snippet

List<Integer> list = List.of(10, 20, 30, 40, 50);
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
list.toArray(array);
System.out.println(Arrays.toString(array));

is:

[10, 20, 30, 40, 50, null, 7, 8, 9, 0]

I have found following code in ArrayList.toArray method:

if (a.length > size)
    a[size] = null;

What is the reason for such behavior? Why the 5th element in may example is null, but not 6?

like image 920
Nolequen Avatar asked Dec 07 '22 09:12

Nolequen


1 Answers

Such behaviour is documented in the Javadoc of List::toArray(T[]):

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the list is set to null (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

(Emphasis mine.)

I find it a bit quite very difficult to come up with a concrete example, but at least the position of the null element is equal to the original length of the list prior to calling toArray.

like image 85
MC Emperor Avatar answered Dec 09 '22 21:12

MC Emperor