Arreglos
## Objetivos de Aprendizaje
- Crear e inicializar arreglos
- Acceder y modificar elementos del arreglo
- Iterar sobre arreglos
- Trabajar con arreglos bidimensionales
## Declarando Arreglos
### Sintaxis
```java
// Declaración
int[] numbers; // Preferido
int numbers[]; // También válido (estilo C)
// Creación
numbers = new int[5];
// Declaración + Creación
int[] numbers = new int[5];
```
### Inicialización
```java
// Por tamaño (valores por defecto)
int[] numbers = new int[3];
// [0, 0, 0]
boolean[] flags = new boolean[2];
// [false, false]
String[] names = new String[2];
// [null, null]
// Con valores
int[] numbers = {1, 2, 3, 4, 5};
String[] fruits = {"Apple", "Banana", "Orange"};
```
## Longitud del Arreglo
```java
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // 5
```
## Accediendo a Elementos
### Índice
```java
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]); // Primer elemento: 10
System.out.println(numbers[4]); // Último elemento: 50
System.out.println(numbers[numbers.length - 1]); // Último elemento
```
### Modificando Elementos
```java
int[] numbers = {10, 20, 30};
numbers[0] = 15; // Cambiar primer elemento
numbers[2] = 35; // Cambiar último elemento
```
### ArrayIndexOutOfBoundsException
```java
int[] numbers = {1, 2, 3};
// numbers[5] = 10; // ¡Error en tiempo de ejecución!
```
## Iterando Arreglos
### Ciclo for
```java
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
```
### for-each Mejorado
```java
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
```
### Ciclo while
```java
int[] numbers = {1, 2, 3, 4, 5};
int i = 0;
while (i < numbers.length) {
System.out.println(numbers[i]);
i++;
}
```
## Operaciones Comunes
### Suma y Promedio
```java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum + ", Average: " + average);
```
### Encontrar Máximo
```java
int[] numbers = {3, 7, 2, 9, 4};
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Max: " + max);
```
### Contar Coincidencias
```java
int[] numbers = {1, 2, 3, 2, 4, 2, 5};
int target = 2;
int count = 0;
for (int num : numbers) {
if (num == target) {
count++;
}
}
System.out.println("Count: " + count);
```
## Clase de Utilidades Arrays
### java.util.Arrays
```java
import java.util.Arrays;
// Ordenar
int[] numbers = {3, 1, 4, 1, 5, 9};
Arrays.sort(numbers);
// Llenar
int[] arr = new int[5];
Arrays.fill(arr, 10); // [10, 10, 10, 10, 10]
// Búsqueda Binaria (debe estar ordenado)
int index = Arrays.binarySearch(numbers, 4);
// Copiar
int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] partial = Arrays.copyOf(numbers, 3);
// Comparar
boolean equal = Arrays.equals(arr1, arr2);
// toString
System.out.println(Arrays.toString(numbers));
```
## Arreglos Bidimensionales
### Declaración
```java
int[][] matrix = new int[3][4]; // 3 filas, 4 columnas
```
### Inicialización de Matriz
```java
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
```
### Accediendo
```java
System.out.println(matrix[0][0]); // Primer elemento: 1
System.out.println(matrix[2][2]); // Último elemento: 9
matrix[1][2] = 10; // Modificar elemento
```
### Iterando
```java
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%d ", matrix[i][j]);
}
System.out.println();
}
```
### Matrix for-each
```java
for (int[] row : matrix) {
for (int num : row) {
System.out.printf("%d ", num);
}
System.out.println();
}
```
## Arreglos Irregulares
### Diferentes Longitudes de Filas
```java
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // 2 elementos
jagged[1] = new int[4]; // 4 elementos
jagged[2] = new int[1]; // 1 elemento
// O con inicialización
int[][] jagged = {
{1, 2},
{3, 4, 5, 6},
{7}
};
```
## Arreglos vs ArrayList
| Característica | Arreglo | ArrayList |
|----------------|---------|-----------|
| Tamaño | Fijo | Dinámico |
| Rendimiento | Más rápido | Ligeramente más lento |
| Tipo | Primitivos y Objetos | Solo Objetos |
| API | Limitada | Rica en métodos |
## Resumen
- Arreglos: `tipo[] nombre = new tipo[tamaño]` o `tipo[] nombre = {valores}`
- Acceso: `arreglo[índice]`
- Longitud: `arreglo.length` (propiedad, no método)
- Iterar: ciclo for regular o for-each mejorado
- Utilidad Arrays: sort, fill, copy, binarySearch, equals
- Arreglos 2D: `int[][] matriz = new int[filas][cols]`
- Los arreglos tienen tamaño fijo; usa ArrayList para colecciones dinámicas
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →