Escolar Documentos
Profissional Documentos
Cultura Documentos
Linguagem de Programao II
1
Arrays
FJN | Faculdade de Juazeiro do Norte
Bacharelado em Sistemas de Informao
Linguagem de Programao II
Prof. Sidney Lima
Arrays
Um array uma estrutura de dados consistindo em itens de
dados do mesmo tipo relacionados.
Os arrays so objetos, portanto, considerados tipos por
referncia.
Para referenciar um elemento do
array deve-se utilizar uma
expresso de acesso ao
array, que inclui o nome do
array seguido pelo nmero da
posio do elemento no array
(dentro de colchetes)
O nmero de posio do
elemento chamado de ndice
ou subscrito do elemento.
FJN | SI | LP2
PROF. SIDNEY
C[ 0 ]
-45
C[ 1 ]
C[ 2 ]
C[ 3 ]
72
C[ 4 ]
154
C[ 5 ]
89
Arrays
Cada objeto de array conhece seu prprio tamanho e
armazena-o em uma varivel de instncia denominada
length. A expresso c.length acessa o campo length do array c
para determinar o comprimento do array.
Algumas operaes:
C
soma = c[1]+c[2]+c[3]
x = c[3]/8
FJN | SI | LP2
PROF. SIDNEY
C[ 0 ]
-45
C[ 1 ]
C[ 2 ]
C[ 3 ]
72
C[ 4 ]
154
C[ 5 ]
89
length
FJN | SI | LP2
PROF. SIDNEY
C[ 0 ]
C[ 1 ]
C[ 2 ]
C[ 3 ]
C[ 4 ]
C[ 5 ]
length
FJN | SI | LP2
PROF. SIDNEY
FJN | SI | LP2
PROF. SIDNEY
int[] array;
System.out.printf("%s%8s","Index","Value");
10
11
12
System.out.printf("%5d%8d\n",counter,array[counter]);
}
}
continua >>
13 }
FJN | SI | LP2
PROF. SIDNEY
Exemplo:
int[] n = { 10, 20, 30, 40, 50}
FJN | SI | LP2
PROF. SIDNEY
n[ 0 ]
10
n[ 1 ]
20
n[ 2 ]
30
n[ 3 ]
40
n[ 4 ]
50
length
int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
int total = 0;
total += array[counter];
10
11
12
13 }
FJN | SI | LP2
PROF. SIDNEY
10
System.out.println("lista.length: "+lista.length);
System.out.println("lista[2]: "+lista[2]);
lista
0 22
10
lista[2] = 99;
1 44
11
System.out.println("lista[2]: "+lista[2]);
2 66
12
13
3 88
}
int[]
14 }
FJN | SI | LP2
PROF. SIDNEY
11
Arrays
Observao:
Para a instruo:
System.out.println("Array de Inteiros: "+lista);
A sada ser algo como:
Array de Inteiros: [I@3e25a5
O que significa uma referncia para um array de ints. Isto
acontece porque estamos tentando imprimir um objeto, logo, o
que apresentado na tela corresponde a
type-id@mem-addr
onde type-id um identificador de tipo e mem-addr o
endereo de memria onde o objeto est armazenado. Neste
caso, type-id [I (que significa um array cujos elementos
possuem o tipo int) e mem-addr 3e25a5.
FJN | SI | LP2
PROF. SIDNEY
12
System.out.println("lista.length: "+lista.length);
10
lista[2] = 99;
11
System.out.println("lista[2]: "+lista[2]);
12
print(lista);
13
FJN | SI | LP2
0 22
1 44
2 66
3 88
int[]
continua >>
PROF. SIDNEY
13
15
16
System.out.print(a[i]+" ");
17
18
System.out.println();
}
19 }
FJN | SI | LP2
PROF. SIDNEY
14
PROF. SIDNEY
15
int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
int total = 0;
total += number;
10
11
12
PROF. SIDNEY
16
Cpia de Arrays
Como se sabe, um array um objeto e, como qualquer objeto,
seu nome na realidade o nome de uma referncia a este
objeto. Consequentemente, atribuir um array a outro no
duplica o array; isto meramente atribui uma outra referncia
ao mesmo objeto.
Desta forma, se as instrues seguintes fossem acrescentadas
ao cdigo anteriormente exibido, teramos o que est
representado na figura ao lado:
int[] lista2;
lista2 = lista;
lista
0 22
lista2
1 44
2 66
3 88
int[]
FJN | SI | LP2
PROF. SIDNEY
17
Cpia de Arrays
Para copiar o prprio objeto array, voc deve copiar cada um
de seus elementos. A maneira mais eficiente de fazer isto
usar o mtodo System.arraycopy().
Sintaxe:
arraycopy(src,srcPos,dest,destPos,length)
onde src o array de origem, srcPos o ndice do primeiro
elemento do array de origem a ser copiado, dest o array de
destino, destPos o ndice onde o primeiro elemento deve
ser copiado no array de destino, e length o nmero de
elementos a serem copiados.
FJN | SI | LP2
PROF. SIDNEY
18
Cpia de Arrays
Exemplo: arraycopy(lista,4,lista2,2,3)
Indica que haver cpia de 3 elementos de lista[] para lista2[]:
lista
int[]
22
lista2
33
44
66
55
77
66
88
77
88
99
int[]
PROF. SIDNEY
19
print(lista);
System.out.println("lista2: "+lista2);
print(lista2);
System.out.println("lista2: "+lista2);
10
print(lista2);
11
lista2[1] = 11;
12
print(lista);
13
print(lista2);
14
FJN | SI | LP2
PROF. SIDNEY
continua >>
20
16
System.out.println("lista2: "+lista2);
17
print(lista2);
18
19
System.out.println("lista2: "+lista2);
20
print(lista2);
O mtodo System.arraycopy()
tambm funciona para
21 }
deslocar um segmento de
22 public static void print(int[] a) {
elementos dentro de um
23
for (int i=0; i<a.length; i++)
mesmo array.
24
System.out.print(a[i]+" ");
25
26
System.out.println();
}
utilizar foreach
27 }
FJN | SI | LP2
PROF. SIDNEY
21
FJN | SI | LP2
PROF. SIDNEY
22
FJN | SI | LP2
PROF. SIDNEY
23
Exerccio
import javax.swing.JOptionPane;
public class OrdenaValores {
public static void main(String[] args) {
int array[] = new int[5]; //cria um array com 5 elementos
String saidaDigitada = "Array digitado: ";
for (int i=0;i<5;i++) { //armazena elementos no array
array[i]=Integer.parseInt(JOptionPane.showInputDialog(null,
"Fornea o nmero "+(i+1)+" entre 0 e 100: "));
saidaDigitada += array[i]+" - ";
}
continua >>
FJN | SI | LP2
PROF. SIDNEY
24
Exerccio
continuao >>
array = ordenaArrayInt(array);
String saidaOrdenada = "Array ordenado: ";
for (int i = 0; i < array.length; i++)
saidaOrdenada += array[i] + " - ";
saidaDigitada = removeTraco(saidaDigitada);
saidaOrdenada = removeTraco(saidaOrdenada);
JOptionPane.showMessageDialog(null, saidaDigitada + "\n" +
saidaOrdenada);
System.exit(0);
}
continua >>
FJN | SI | LP2
PROF. SIDNEY
25
Exerccio
continuao >>
public static int[] ordenaArrayInt(int arr[]) {
int x, y, aux;
for (x = 0; x < arr.length; x++)
for (y = 0; y < arr.length; y++) {
if (arr[x]<arr[y]) {
aux=arr[y];
arr[y]=arr[x];
arr[x]=aux;
}
}
return (arr);
}
continua >>
FJN | SI | LP2
PROF. SIDNEY
26
Exerccio
continuao >>
public static String removeTraco(String str) {
.
.
.
}
}
FJN | SI | LP2
PROF. SIDNEY
27
Exerccio
continuao >>
public static String removeTraco(String str) {
str = str.substring(0, str.length()-2);
return str;
}
}
FJN | SI | LP2
PROF. SIDNEY
28
char,
char[] strings = {'J','a','v','a'};
e arrays do tipo
Object,
Object[] objetos = {x, y, z};
FJN | SI | LP2
PROF. SIDNEY
29
FJN | SI | LP2
PROF. SIDNEY
30
Exerccio
public class TestArgs {
public static void main(String[] args) {
System.out.println("args.length: "+args.length);
for (int i = 0; i < args.length; i++)
System.out.println("args["+i+"]: "+args[i]);
System.out.println();
for (int i = args.length-1; i >= 0; i--)
System.out.println("args["+i+"]: "+args[i]);
}
}
FJN | SI | LP2
PROF. SIDNEY
31
FJN | SI | LP2
PROF. SIDNEY
32
FJN | SI | LP2
PROF. SIDNEY
33
FJN | SI | LP2
PROF. SIDNEY
34
FJN | SI | LP2
PROF. SIDNEY
35
Arrays Bidimensionais
Uma array bidimensional permite a criao de vetores com
mais de um ndice. Esta caracterstica possibilita que os valores
sejam armazenados na forma de matrizes de qualquer
dimenso.
O exerccio apresentado a seguir utiliza um array bidimensional
para coletar duas notas de trs alunos (um total de seis notas).
Uma vez armazenadas, o programa solicita ao usurio o
nmero de um aluno para mostrar suas notas e a mdia delas.
FJN | SI | LP2
PROF. SIDNEY
36
Arrays Bidimensionais
Uma array bidimensional permite a criao de vetores com
mais de um ndice. Esta caracterstica possibilita que os valores
sejam armazenados na forma de matrizes de qualquer
dimenso.
O exerccio apresentado a seguir utiliza um array bidimensional
para coletar duas notas de trs alunos (um total de seis notas).
Uma vez armazenadas, o programa solicita ao usurio o
nmero de um aluno para mostrar suas notas e a mdia delas.
FJN | SI | LP2
PROF. SIDNEY
37
Exerccio
Os aspectos mais importantes do exerccio a seguir so:
So coletadas e armazenadas duas notas de trs alunos no
array no formato de uma tabela; o que feito atravs da
estrutura de loops aninhados e do comando abaixo:
notas[aluno][nota]=Float.parseFloat(JOptionPane.showInputDialog
(null,"Fornea a nota "+(nota+1)+" do aluno "+(aluno+1)));
Notas
0
Alunos
0
Aluno1
Nota1 ndice[0][0]
Nota2 ndice[0][1]
Aluno2
Nota1 ndice[1][0]
Nota2 ndice[1][1]
Aluno3
Nota1 ndice[2][0]
Nota2 ndice[2][1]
FJN | SI | LP2
PROF. SIDNEY
38
Exerccio
import javax.swing.JOptionPane;
public class CalculaMedias {
public static void main(String[] args) {
float notas[][] = new float[3][2];
int aluno = 0, nota;
while (aluno<3)
{
nota = 0;
while (nota<2)
{
notas[aluno][nota]=
Float.parseFloat(JOptionPane.showInputDialog
(null,"Fornea a nota "+(nota+1)+" do aluno "+(aluno+1)));
nota++;
}
continua >>
FJN | SI | LP2
PROF. SIDNEY
39
Exerccio
continuao >>
aluno++;
}
aluno =
Integer.parseInt(JOptionPane.showInputDialog(null,"Fornea o
nmero do aluno a consultar: "));
JOptionPane.showMessageDialog(null, "CONSULTA DE NOTAS: "+
"\nAluno: "+aluno+
"\nNota1: "+notas[aluno - 1][0]+
"\nNota2: "+notas[aluno - 1][1]+
"\nMedia: "+((notas[aluno-1][0]+notas[aluno-1][1])/2)
);
System.exit(0);
}
}
FJN | SI | LP2
PROF. SIDNEY
40
A sada:
0. Tue Apr 14 17:50:04 BRT 2009
1. ABCDE
2. java.util.Random@190d11
3. [I@a90653
4. null
Date
"ABCDE"
String
3
4
Random
Object[]
0 22
1 33
2 44
int[]
PROF. SIDNEY
41
Date
"ABCDE"
String
3
4
Random
Object[]
0 22
1 33
2 44
int[]
FJN | SI | LP2
PROF. SIDNEY
42
a[0]
a[1]
a[2]
a[3]
=
=
=
=
new java.util.Date();
"ABCDE";
new java.util.Random();
new int[] {22,33,44};
Date
"ABCDE"
String
3
4
Random
Object[]
0 22
1 33
2 44
int[]
FJN | SI | LP2
PROF. SIDNEY
43
Date
"ABCDE"
String
3
4
Random
Object[]
0 22
1 33
2 44
int[]
FJN | SI | LP2
PROF. SIDNEY
44
0
1
print(a);
"ABCDE"
String
PROF. SIDNEY
4
Random
Object[]
0 22
1 33
2 44
int[]
45
A Classe java.
java.util.Arrays
Java inclui uma classe "utilitria" especial para processamento
de arrays. O nome desta classe Arrays; ela est definida no
pacote java.util.
O prximo programa ilustra os mtodos sort(),
binarySearch(), fill(), e equals() da classe
java.util.Arrays.
FJN | SI | LP2
PROF. SIDNEY
46
print(a);
Arrays.sort(a);
print(a);
10
System.out.println("Arrays.binarySearch(a,44): "+k);
11
System.out.println("a["+k+"]:"+a[k]);
12
k = Arrays.binarySearch(a,45);
13
System.out.println("Arrays.binarySearch(a,45): "+k);
continua >>
FJN | SI | LP2
PROF. SIDNEY
47
15
print(b);
16
Arrays.fill(b, 55);
17
print(b);
18
System.out.println("Arrays.equals(a,b): "+Arrays.equals(a,b));
19 }
20
21
22
23
System.out.print(a[i]+" ");
24
25
System.out.println();
}
26 }
FJN | SI | LP2
PROF. SIDNEY
48
FJN | SI | LP2
PROF. SIDNEY
49
PROF. SIDNEY
50
FJN | SI | LP2
PROF. SIDNEY
51
5
6
// retorna false a menos que a[0] <= a[1] <= a[2] <= ...
10
11
return true;
}
12
continua >>
FJN | SI | LP2
PROF. SIDNEY
52
14
15
if (a==null||a.length==0) return;
16
System.out.print("{"+a[0]);
17
18
System.out.print(","+a[i]);
19
20
System.out.println("}");
}
21
continua >>
FJN | SI | LP2
PROF. SIDNEY
53
24
25
26
27
a[i] = random.nextInt(range);
28
return a;
29 }
30
continua >>
FJN | SI | LP2
PROF. SIDNEY
54
32
33
34
35
36
37
return aa;
38 }
39
continua >>
FJN | SI | LP2
PROF. SIDNEY
55
42
43
a[i]=aj;
44
a[j]=ai;
45
46 }
FJN | SI | LP2
PROF. SIDNEY
56
IntArrays.print(a);
System.out.println("IntArrays.isSorted(a): "+IntArrays.isSorted(a));
Arrays.sort(a);
IntArrays.print(a);
10
System.out.println("IntArrays.isSorted(a): "+IntArrays.isSorted(a));
11
IntArrays.swap(a, 2, 4);
12
IntArrays.print(a);
13
System.out.println("IntArrays.isSorted(a): "+IntArrays.isSorted(a));
continua >>
FJN | SI | LP2
PROF. SIDNEY
57
a = IntArrays.resized(a, 10);
15
IntArrays.print(a);
16
a = IntArrays.resized(a, 5);
17
IntArrays.print(a);
18
19 }
FJN | SI | LP2
PROF. SIDNEY
58
FJN | SI | LP2
PROF. SIDNEY
59
FJN | SI | LP2
PROF. SIDNEY
60
Questes de Reviso
1.
2.
3.
4.
5.
6.
FJN | SI | LP2
PROF. SIDNEY
61
14
15
janela.setVisible(true);
16
17
janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18
19 }
FJN | SI | LP2
PROF. SIDNEY
62