The method toArray
of class ArrayList
returns an array of objects. How can it be done to return an array of strings (StringList [])?
Should it be done like this?
ArrayList<String> nombreArrayList = new ArrayList<String>();
The method toArray
of class ArrayList
returns an array of objects. How can it be done to return an array of strings (StringList [])?
Should it be done like this?
ArrayList<String> nombreArrayList = new ArrayList<String>();
First of all, the% toArray();
method will return an Array that contains elements of the same type as the ArrayList.
Here is the definition of the method, where T is the type that contains and returns the method.
public <T> T[] toArray(T[] a)
Here is an example of how it works.
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("Juan");
arrList.add("Pedro");
arrList.add("Pablo");
arrList.add("Mateo");
arrList.add("Marcos");
//tienes un ArrayList, ahora tienes que declarar un Array del mismo tipo
String arr[] = new String[arrList.size()];
arr = arrList.toArray(arr);
Postado: the String with the "S" in uppercase, since it is the class wrapper of string in with "s" lowercase.
There is a method to return an array of the type of data you are looking for, as indicated in List#toArray(T[] a)
. The example would be like this:
List<String> lista = new ArrayList<>(Arrays.asList("hello", "world"));
String[] arreglo = lista.toArray(new String[lista.size()]);
System.out.println(lista);
System.out.println(Arrays.toString(arreglo));