Un array es un objeto contenedor que almacena un número fijo de valores de un solo tipo. La longitud de un array se establece cuando éste se crea. Después de su creación su longitud es fija. Ya ha visto un ejemplo de un array en el métodomainde la aplicación «Hola mundo». Esta sección trata los arrays con más detalle.
Un array de diez elementos
A cada unidad del array se le llama element y a cada elemento se accede por su índice numérico. Como se muestra en la ilustración anterior, la numeración empieza por 0. Al noveno elemento, por ejemplo, se accederá con el índice 8.
El siguiente programa,
ArrayDemo, crea un array de enteros, lo rellena con algunos valores e imprime cada valor a la salida estándar.La salida de este programa es:/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class ArrayDemo { public static void main(String[] args) { int[] anArray; // declara un array de enteros anArray = new int[10]; // reserva memoria para 10 enteros anArray[0] = 100; // inicializa el primer elemento anArray[1] = 200; // inicializa el segundo elemento anArray[2] = 300; // etc. anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Elemento en el índice 0: " + anArray[0]); System.out.println("Elemento en el índice 1: " + anArray[1]); System.out.println("Elemento en el índice 2: " + anArray[2]); System.out.println("Elemento en el índice 3: " + anArray[3]); System.out.println("Elemento en el índice 4: " + anArray[4]); System.out.println("Elemento en el índice 5: " + anArray[5]); System.out.println("Elemento en el índice 6: " + anArray[6]); System.out.println("Elemento en el índice 7: " + anArray[7]); System.out.println("Elemento en el índice 8: " + anArray[8]); System.out.println("Elemento en el índice 9: " + anArray[9]); } }Elemento en el índice 0: 100 Elemento en el índice 1: 200 Elemento en el índice 2: 300 Elemento en el índice 3: 400 Elemento en el índice 4: 500 Elemento en el índice 5: 600 Elemento en el índice 6: 700 Elemento en el índice 7: 800 Elemento en el índice 8: 900 Elemento en el índice 9: 1000En una situación de programación del «mundo real» probablemente habría utilizado una de las estructuras de bucle para recorrer cada elemento del array en vez de escribir cada línea como en el ejemplo. Aún así, este ejemplo ilustra claramente la sintaxis del array. Aprenderá acerca de las diferentes estructuras de bucle (
for,whileydo-while) en la sección Sentencias de control de flujo.Declarar una variable para que se refiera a un array
El programa anterior declaraanArraycon el siguiente código:int[] anArray; // declara un array de enterosIgual que las declaraciones de variables de otros tipos, la declaración de un array tiene dos componentes: el tipo del array y su nombre. El tipo del array se escribe
tipo[], dondetipoes el tipo de dato de los elementos contenidos, los corchetes cuadrados son símbolos especiales que indican que esta variable contiene un array. El tamaño del array no es parte de su tipo (por lo que los corchetes están vacíos). El nombre de un array puede ser cualquier cosa, siempre que cumpla con las reglas y convenios que ya se han tratdo en la sección nomenclatura. Igual que con las variables de otros tipos, la declaración realmente no crea un array — solamente se dice al compilador que esta variable va a contener un array del tipo indicado.Puede declarar arrays de otros tipo de forma similar:
byte[] unArrayDeBytes; short[] unArrayDeShorts; long[] unArrayDeLongs; float[] unArrayDeFloats; double[] unArrayDeDoubles; boolean[] unArrayDeBooleans; char[] unArrayDeChars; String[] unArrayDeStrings;También puede colocar los corchetes cuadrados después del nombre del array:
Sin embargo, por convenio se desaconseja esta forma, los corchetes identifican el tipo del array y deberían aparecer en la designación del tipo.float unArrayDeFloats[]; // esta forma está desaconsejadaCrear, inicializar y acceder a un array
Una de las formas de crear un array es con el operadornew. La siguiente sentencia del programaArrayDemoreserva un array con suficiente memoria para diez elementos enteros y asigna el array a la variableanArray.Si faltara esta sentencia, el compilador mostraría un error como el siguiente y la compilación fallaría:anArray = new int[10]; // crea un array de enterosLas siguientes líneas asignan valores a cada uno de los elementos del array:ArrayDemo.java:4: Variable anArray may not have been initialized.A los elementos del array se accede por su índice numérico:anArray[0] = 100; // inicializa el primer elemento anArray[1] = 200; // inicializa el segundo elemento anArray[2] = 300; // etc.También puede utilizar la sintaxis abreviada para crear e inicializar un array:System.out.println("Elemento 1 en el índice 0: " + anArray[0]); System.out.println("Elemento 2 en el índice 1: " + anArray[1]); System.out.println("Elemento 3 en el índice 2: " + anArray[2]);En esta caso la longitud del array viene determinada por la cantidad de valores proporcionados entre { y }.int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};También puede declarar un array de arrays (conocido como un array multidimensional) utilizando dos o más conjuntos de corchetes cuadrados, por ejemplo
String[][] nombres. Por lo tanto, a cada elemento se accederá por un número correspondiente de valores de índice.En el lenguaje de programación Java un array multidimensional es simplemente un array cuyos componentes son, también, arrays. Esto es distinto de los arrays en C o Fortran. Esto trae como consecuencia que las filas pueden variar en longitud, como se muestra en el siguiente programa MultiDimArrayDemo:
La salida de este programa es:class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; System.out.println(names[0][0] + names[1][0]); //Mr. Smith System.out.println(names[0][2] + names[1][1]); //Ms. Jones } }Mr. Smith Ms. JonesPuede utilizar la propiedad
lengthpara determinar la longitud de un array. El códigomostrará el tamaño del array en la salida estándar.System.out.println(anArray.length);Copiar arrays
La claseSystemcontiene el métodoarraycopyque se puede utilizar para copiar eficientemente un array a otro:Los dos argumentos de tipopublic static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)Objectindican el array desde el que copiar y el array hacia el que copiar. Los tres argumentos de tipointindican la posición de inicio del array de origen, la posición de inicio del array de destino y la cantidad de elementos que se copiarán.El siguiente programa,
ArrayCopyDemo, declara un array de elementos de tipocharque componen la palabra «decaffeinated». Utilizaarraycopypara copiar una subsecuencia de componentes del array en un segundo array:/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }La salida de este programa es:
caffein
ATENCIÓN: La traducción de esta documentación es un esfuerzo personal y voluntario. NO es un documento oficial del propietario de la tecnología Java, Oracle, ni está patrocinado por esta empresa.
Los documentos originales y actualizados (en inglés) están disponibles en: http://docs.oracle.com/javase/tutorial/. La versión disponible en este sitio es la publicada en Marzo de 2008 (más información en: "What's new and What's Old? The History of the Tutorial").
Dirige cualquier comentario, petición, felicitación, etc. a tutorialesjava@codexion.com.
Si quieres ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesitas que se traduzca algún capítulo en concreto puedes invitarme a un café: