Assign to Array result of ArrayList () Java

0

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>();
    
asked by Roman345 01.11.2016 в 20:29
source

2 answers

0

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.

    
answered by 01.11.2016 / 20:47
source
2

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));
    
answered by 01.11.2016 в 20:38