Last active
February 17, 2017 02:00
-
-
Save javerosanonimos/f5162bc99a83fe9040962cc44d3cc978 to your computer and use it in GitHub Desktop.
Código de ejemplo para convertir un array a una lista
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
@Autor: www.javerosanonimos.com | |
Twitter: @javerosanonimos | |
Facebook: www.facebook.com/JaverosAnonimos | |
e-mail: javerosanonimos@gmail.com | |
**/ | |
public class EjemploConvertirListaAUnArray { | |
public static void main(final String arg[]) { | |
// Creamos e inicializamos la lista que se convertira a un array | |
final List listaEjemplo = crearListaEjemploString(); | |
// Convirtiendo lista utilizando la implementacion del metodo .toArray() | |
convertirListaAUnArrayPrimerOpcion(listaEjemplo); | |
// Convirtiendo lista utilizando la implementacion del metodo | |
// .toArray(array[]) | |
convertirListaAUnArraySegundaOpcion(listaEjemplo); | |
} | |
private static void convertirListaAUnArraySegundaOpcion(final List listaEjemplo) { | |
// Como sabemos los arreglos debemos inicializarlos con un tamaño y en | |
// este caso el tamaño del array debe ser igual o mayor al tamaño de | |
// la lista (si la lista sera un array lo correcto es que sean del mismo | |
// tamaño) | |
String[] arrayEjemplo = new String[listaEjemplo.size()]; | |
// el metodo .toArray(array[]) nos permite convertir la lista al array | |
// recibiendo como parametro el array con el tipo de dato que | |
// necesitamos (debe ser igual al tipo de la lista) | |
arrayEjemplo = listaEjemplo.toArray(arrayEjemplo); | |
for (final String string : arrayEjemplo) { | |
System.err.println("Recorriendo array con un tipo de dato especifico: " + string); | |
} | |
} | |
private static void convertirListaAUnArrayPrimerOpcion(final List listaEjemplo) { | |
// el metodo .toArray() nos permite convertir una lista a un array de | |
// objetos | |
final Object[] array = listaEjemplo.toArray(); | |
for (final Object object : array) { | |
System.err.println("Recorriendo array de tipo Object: " + object); | |
} | |
} | |
private static List crearListaEjemploString() { | |
final List listaEjemplo = new ArrayList(); | |
listaEjemplo.add("HOLA MUNDO"); | |
listaEjemplo.add("HOLA MUNDO DOS"); | |
listaEjemplo.add("HOLA MUNDO TRES"); | |
listaEjemplo.add("HOLA MUNDO CUATRO"); | |
return listaEjemplo; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment