Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda