0

I have some code like this :

    String[] colors = {"black", "blue", "yellow", "red", "pink", "green", "cyan"};
    String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
    LinkedList<String> links = new LinkedList<>(Arrays.asList(colors));
    System.out.println(links);
    colors = links.toArray(alphabets);
    System.out.println(Arrays.asList(colors));

and its output is :

[black, blue, yellow, red, pink, green, cyan]
[black, blue, yellow, red, pink, green, cyan, null, I]

what is that null in the second output line?and why?

Amin
  • 138
  • 7
  • 12
    [RTM](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#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._ – 001 Mar 30 '18 at 15:16

2 Answers2

5

The best source of answers when you have a question regarding a particular behavior of a method is to check the documentation.

The java doc states:

toArray(T[] a)

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.)

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
3

This is how LinkedList.toArray works. Basically you ask the list containing 7 elements to be wrapped into the array of 9 elements size.

The 7-th element is null because of this code inside toArray method:

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

and the 8-th element is remaining I from the initial state of this array.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241