Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!