ArrayList: a list that grows · ArrayList: una lista que crece
A list that can grow
- An array has a fixed size. Once you make it, the length cannot change.
- An
ArrayListis a list that can grow and shrink while the program runs. - You must import it at the top of the file:
import java.util.ArrayList;.
Una lista que puede crecer
- Un array tiene un tamaño fijo. Una vez creado, su longitud no puede cambiar.
- Un
ArrayListes una lista que puede crecer y encogerse mientras el programa se ejecuta. - Debes importarlo en la parte superior del archivo:
import java.util.ArrayList;.
Making an ArrayList
- Write the type of the items inside
<...>. This is the AP CSA way. ArrayList<String>holds text.ArrayList<Integer>holds whole numbers.- A new list starts empty, with size
0.
Crear un ArrayList
- Escribe el tipo de los elementos dentro de
<...>. Esta es la forma recomendada para AP CSA. ArrayList<String>almacena texto.ArrayList<Integer>almacena números enteros.- Una nueva lista comienza vacía, con tamaño
0.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
System.out.println(names.size()); // 0
names.add("Ann");
names.add("Bo");
System.out.println(names.size()); // 2
System.out.println(names); // [Ann, Bo]
}
}
The five methods you need
list.size()— how many items are in the list.list.add(x)— putxat the end of the list.list.get(i)— the item at positioni(the first position is 0).list.set(i, x)— replace the item at positioniwithx.list.remove(i)— take out the item at positioni; later items shift left.
Los cinco métodos esenciales
list.size()— cuántos elementos hay en la lista.list.add(x)— añadexal final de la lista.list.get(i)— obtiene el elemento en la posicióni(la primera posición es 0).list.set(i, x)— reemplaza el elemento en la posicióniconx.list.remove(i)— elimina el elemento en la posicióni; los elementos posteriores se desplazan hacia la izquierda.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruit = new ArrayList<String>();
fruit.add("apple");
fruit.add("pear");
fruit.add("plum");
System.out.println(fruit.get(0)); // apple
fruit.set(1, "grape"); // pear -> grape
fruit.remove(2); // take out "plum"
System.out.println(fruit); // [apple, grape]
}
}
Numbers need Integer
- An
ArrayListcan only hold objects, not the simple typeint. - So we write
ArrayList<Integer>.Integeris the object form ofint. - Java changes between
intandIntegerfor you. This is called autoboxing. - You can
add(7)anint, andget(0)gives back a value you can use asint.
Los números requieren Integer
- Un
ArrayListsolo puede almacenar objetos, no el tipo primitivoint. - Por lo tanto escribimos
ArrayList<Integer>.Integeres la versión objeto deint. - Java realiza la conversión entre
inteIntegerautomáticamente. Esto se llama autoboxing. - Puedes hacer
add(7)con unint, yget(0)devolverá un valor que puedes usar comoint.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10); // int 10 is boxed into Integer
nums.add(20);
int first = nums.get(0); // unboxed back to int
System.out.println(first + nums.get(1)); // 30
}
}
Two ways to traverse
- An index for-loop uses positions
0tosize() - 1. Use it when you need the index. - An enhanced for-loop (
for (int x : list)) reads each item in turn. Use it when you only need the values. - Both visit every item once, in order.
Dos formas de recorrer
- Un ciclo for con índice utiliza posiciones de
0asize() - 1. Úsalo cuando necesites el índice. - Un ciclo for mejorado (
for (int x : list)) lee cada elemento sucesivamente. Úsalo cuando solo necesites los valores. - Ambos visitan cada elemento una sola vez, en orden.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(8);
// index for-loop
for (int i = 0; i < nums.size(); i++) {
System.out.println("at " + i + ": " + nums.get(i));
}
// enhanced for-loop
int total = 0;
for (int x : nums) {
total = total + x;
}
System.out.println("total " + total); // total 16
}
}
Common mistakes
ArrayListuses.add,.get(i),.size()— not[].- Store objects: use
ArrayList<Integer>, notArrayList<int>.
Errores comunes
ArrayListusa.add,.get(i),.size()— no[].- Almacena objetos: usa
ArrayList<Integer>, noArrayList<int>.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Ahora tú practica
- Cada tarea prellena la estructura básica de la clase — escribe tu código dentro de main, o completa el método mostrado.
- Presiona Run (Ejecutar) para compilar y ejecutar, luego Check answer (Verificar respuesta).
- Tu código se compila y ejecuta en el servidor, así que incluso la primera ejecución es rápida.
An ArrayList grows · Un ArrayList crece
Unlike an array, an ArrayList changes size as you add/remove. · A diferencia de un array, un ArrayList cambia de tamaño a medida que agregas o eliminas elementos.
Complete sumList(ArrayList<Integer> a) so it returns the total of all numbers in the list. An empty list totals 0. Traverse with a loop. · Completa sumList(ArrayList<Integer> a) para que devuelva la suma total de todos los números en la lista. Una lista vacía suma 0. Recorre con un bucle.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete countUp(int n) so it makes a new ArrayList<Integer>, adds the numbers 1, 2, ..., n in order, and returns it. If n is 0, return an empty list. · Completa countUp(int n) para crear un nuevo ArrayList<Integer>, agregar los números 1, 2, ..., n en orden y devolverlo. Si n es 0, devuelve una lista vacía.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete doubleAt(ArrayList<Integer> a, int i). Read the value at index i with get, then use set to store two times that value back at index i. Return nothing (void). · Completa doubleAt(ArrayList<Integer> a, int i). Lee el valor en el índice i con get, luego usa set para almacenar el doble de ese valor nuevamente en el índice i. No retorna nada (void).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.