Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda