Array Creation and Access · Creación y acceso a arrays
| English | Español |
|---|---|
| initializer list/ɪˈnɪʃəlaɪzə lɪst/ | lista inicializadora |
| ArrayIndexOutOfBoundsException/əˈreɪ ˈɪndeks ˈaʊtəv baʊndz ekˈsepʃn/ | ArrayIndexOutOfBoundsException |
Making an array
- Declare an array with a type and
[]:int[] scores; - Create it with
newand a size:int[] scores = new int[5];(five slots). - Or list the values directly:
int[] scores = {85, 90, 78};(an initializer list 初始化列表). - Every slot starts at the type's default (
0forint,nullfor objects).
Crear un array
- Declara un array con un tipo y
[]:int[] scores; - Crea uno con
newy un tamaño:int[] scores = new int[5];(cinco posiciones). - O bien enumera los valores directamente:
int[] scores = {85, 90, 78};(una lista de inicialización 初始化列表). - Cada posición se inicializa con el valor por defecto del tipo (
0paraint,nullpara objetos).
Indexing from zero
- Array elements are numbered from
0; the last index islength - 1. - Access a slot with
scores[i]:scores[0]is the first,scores[2]the third. - Assign with
scores[0] = 100;and read withint x = scores[0];. - Off-by-one on the last index is the most common array bug.
Indexación desde cero
- Los elementos del array se numeran desde
0; el último índice eslength - 1. - Accede a una posición con
scores[i]:scores[0]es el primero,scores[2]el tercero. - Asigna con
scores[0] = 100;y lee conint x = scores[0];. - El error de "fuera de límites" en el último índice es el bug más común en arrays.
The length field
- An array's size is its
lengthfield — no parentheses:scores.length. - (Contrast
String'slength()method, which has parentheses.) lengthis fixed once the array is created — arrays don't resize.- Use
scores.lengthin loop conditions to stay in bounds.
El campo length
- El tamaño de un array es su campo
length— sin paréntesis:scores.length. - (Contrasta con el método
Stringdelength(), que sí lleva paréntesis.) lengthes fijo una vez creado el array; los arrays no cambian de tamaño.- Usa
scores.lengthen las condiciones de los bucles para mantenerse dentro de los límites.
Out of bounds
- A valid index is
0tolength - 1; anything else throws an ArrayIndexOutOfBoundsException 数组下标越界异常. scores[5]on a length-5 array is out of bounds (indices are0–4).- The loop condition
i < scores.lengthkeepsiin range. - Never use
<=withlength— it steps one past the end.
Fuera de límites
- Un índice válido va de
0alength - 1; cualquier otro provoca un ArrayIndexOutOfBoundsException 数组下标越界异常. scores[5]en un array de longitud 5 está fuera de límites (los índices son0–4).- La condición del bucle
i < scores.lengthmantieneidentro del rango. - Nunca uses
<=conlength— te saltas un paso más allá del final.
Array size is length (a field, NO parentheses); String length is length() (a method, WITH parentheses). Mixing them up won't compile. And valid indices are 0 to length - 1 — scores[scores.length] is one past the end and throws an ArrayIndexOutOfBoundsException. Loop with i < scores.length, never i <= scores.length.
El tamaño del array es length (un campo, SIN paréntesis); la longitud de String es length() (un método, CON paréntesis). Confundirlos dará error de compilación. Y los índices válidos van de 0 a length - 1 — scores[scores.length] es un paso más allá del final y lanza un ArrayIndexOutOfBoundsException. Buclea con i < scores.length, nunca i <= scores.length.
Creating and accessing an array:
int[] a = {10, 20, 30};— length3, indices0,1,2.a[0]is10;a[2]is30;a.lengthis3.a[3]throws ArrayIndexOutOfBoundsException (no index 3).
Crear y acceder a un array:
int[] a = {10, 20, 30};— longitud3, índices0,1,2.a[0]es10;a[2]es30;a.lengthes3.a[3]lanza ArrayIndexOutOfBoundsException (no existe el índice 3).
Create an array with new type[size] or an initializer list {...}. Elements are indexed from 0 to length - 1, accessed as a[i]. The size is the length field (no parentheses). An index outside 0..length-1 throws an ArrayIndexOutOfBoundsException — loop with i < a.length.
Crea un array con new type[size] o una lista de inicialización {...}. Los elementos se indexan desde 0 hasta length - 1, accediéndose como a[i]. El tamaño es el campo length (sin paréntesis). Un índice fuera del rango 0..length-1 lanza un ArrayIndexOutOfBoundsException — buclea con i < a.length.
Indexing an array from 0 · Indexar un array desde 0
a[0]=10, a[1]=20, a[2]=30; a.length is 3. · a[0]=10, a[1]=20, a[2]=30; a.length es 3.
For int[] a = {10, 20, 30}; what is a[0]? · Para int[] a = {10, 20, 30}; ¿cuál es a[0]?
Arrays are indexed from 0, so a[0] is the first element, 10. · Los arrays se indexan desde 0, por lo que a[0] es el primer elemento, 10.
How do you get the size of an array a? · ¿Cómo obtienes el tamaño de un array a?
Array size is the length FIELD (no parentheses). · El tamaño del array es el campo length (sin paréntesis).
For int[] a = {10, 20, 30}; what is a.length? · Para int[] a = {10, 20, 30}; ¿cuál es a.length?
Three elements → length 3. · Tres elementos → length 3.
For a length-5 array, accessing index 5 (a[5])... · Para un array de longitud 5, acceder al índice 5 (a[5])...
Valid indices are 0..4; index 5 is out of bounds. · Los índices válidos son 0..4; el índice 5 está fuera de límites.
String uses length() (a method) while an array uses length (a field). · String usa length() (un método) mientras que un array usa length (un campo).
Different syntax — parentheses for String, none for arrays. · Diferente sintaxis — paréntesis para String, ninguno para arrays.