Consider the following code:
import java.util.*;
public class ArrayQuestion{
public static void main(String[] args){
List<String> list = new ArrayList<>();
list.add("Chocolate");
list.add("Vanilla");
//Converting the List to an Array
Object[] objectArray = list.toArray();
So the toArray method returns an array of default type Object[]. Let's say I wanted to create a String array, I read that I would pass a string[] object in to the toArray method.
String[] stringArray = list.toArray(new String[0]);
I read that the advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the return value.
Could somebody please explain this, I looked up the toArray(String[] stringArray) method in the Java API. I still do not understand what return value the above statement is alluding too.
My question is specifically about parameter passed in to the toArray method and why it is 0 and how passing 0 creates an array of the proper size of the list.
When you pass an array that is too small to the toArray method, it creates an array of the same class but with the correct size. An empty array (length 0) is perfect for that.