Array Creation and Access · Criação e Acesso a Arrays
| English | Português |
|---|---|
| initializer list/ɪˈnɪʃəlaɪzə lɪst/ | lista de inicializadores |
| 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).
Criando um array
- Declare um array com um tipo e
[]:int[] scores; - Crie-o com
newe um tamanho:int[] scores = new int[5];(cinco posições). - Ou liste os valores diretamente:
int[] scores = {85, 90, 78};(uma lista inicializadora). - Cada posição começa com o padrão do 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.
Indexação a partir de zero
- Elementos de array são numerados a partir de
0; o último índice élength - 1. - Acesse uma posição com
scores[i]:scores[0]é o primeiro,scores[2]o terceiro. - Atribua com
scores[0] = 100;e leia comint x = scores[0];. - Erro off-by-one no último índice é o bug de array mais comum.
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.
O campo length
- O tamanho de um array é seu campo
length— sem parênteses:scores.length. - (Contraste
String'slength()método, que possui parênteses.) lengthé fixo assim que o array é criado — arrays não redimensionam.- Use
scores.lengthem condições de loop para permanecer dentro dos limites.
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.
Fora dos limites
- Um índice válido vai de
0alength - 1; qualquer outro lançará um ArrayIndexOutOfBoundsException 数组下标越界异常. scores[5]em um array de comprimento 5 está fora dos limites (índices são0–4).- A condição do loop
i < scores.lengthmantémidentro do intervalo. - Nunca use
<=comlength— ele avança uma posição após o 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.
O tamanho do array é length (um campo, SEM parênteses); String length é um length() (um método, COM parênteses). Misturá-los não compilará. E índices válidos são de 0 a length - 1 — scores[scores.length] é uma posição após o final e lançará um ArrayIndexOutOfBoundsException. Faça loop com i < scores.length, nunca com 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).
Criando e acessando um array:
int[] a = {10, 20, 30};— comprimento3, índices0,1,2.a[0]é10;a[2]é30;a.lengthé3.a[3]lançará ArrayIndexOutOfBoundsException (não há í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.
Crie um array com new type[size] ou uma lista de inicialização {...}. Os elementos são indexados de 0 a length - 1, acessados como a[i]. O tamanho é o campo length (sem parênteses). Um índice fora de 0..length-1 lançará um ArrayIndexOutOfBoundsException — faça loop com i < a.length.
Indexing an array from 0 · Indexando um array a partir de 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 é 3.
For int[] a = {10, 20, 30}; what is a[0]? · Para int[] a = {10, 20, 30}; qual é a[0]?
Arrays are indexed from 0, so a[0] is the first element, 10. · Arrays são indexados a partir de 0, então a[0] é o primeiro elemento, 10.
How do you get the size of an array a? · Como você obtém o tamanho do array a?
Array size is the length FIELD (no parentheses). · O tamanho do array é o campo length (sem parênteses).
For int[] a = {10, 20, 30}; what is a.length? · Para int[] a = {10, 20, 30}; qual é a.length?
Three elements → length 3. · Três elementos → length 3.
For a length-5 array, accessing index 5 (a[5])... · Para um array de comprimento 5, acessar o índice 5 (a[5])...
Valid indices are 0..4; index 5 is out of bounds. · Índices válidos são 0..4; índice 5 está fora dos limites.
String uses length() (a method) while an array uses length (a field). · String usa length() (um método) enquanto um array usa length (um campo).
Different syntax — parentheses for String, none for arrays. · Sintaxe diferente — parênteses para String, nenhum para arrays.