ArrayList: a list that grows · ArrayList: một danh sách có thể mở rộng
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;.
Một danh sách có thể mở rộng
- Mảng có kích thước cố định. Sau khi tạo ra, chiều dài không thể thay đổi.
- Một
ArrayListlà danh sách có thể mở rộng và thu gọn trong khi chương trình chạy. - Bạn phải import nó ở đầu file:
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.
Tạo ArrayList
- Viết kiểu dữ liệu của các mục bên trong
<...>. Đây là cách chuẩn AP CSA. ArrayList<String>chứa văn bản.ArrayList<Integer>chứa số nguyên.- Một danh sách mới bắt đầu trống, với kích thước
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.
Năm phương pháp bạn cần biết
list.size()— số lượng mục trong danh sách.list.add(x)— thêmxvào cuối danh sách.list.get(i)— lấy mục tại vị tríi(vị trí đầu tiên là 0).list.set(i, x)— thay thế mục tại vị tríibằngx.list.remove(i)— loại bỏ mục tại vị tríi; các mục sau sẽ dịch sang trái.
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.
Các số cần Integer
- Một
ArrayListchỉ có thể chứa đối tượng, không phải kiểu đơn giảnint. - Vì vậy ta viết
ArrayList<Integer>.Integerlà dạng đối tượng củaint. - Java tự động chuyển đổi giữa
intvàIntegercho bạn. Điều này gọi là autoboxing (tự đóng hộp). - Bạn có thể
add(7)mộtint, vàget(0)sẽ trả về giá trị mà bạn có thể sử dụng nhưint.
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.
Hai cách duyệt danh sách
- Vòng lặp for theo chỉ số sử dụng vị trí từ
0đếnsize() - 1. Dùng khi bạn cần truy cập chỉ số. - Vòng lặp for nâng cao (
for (int x : list)) đọc lần lượt từng mục. Dùng khi bạn chỉ cần lấy giá trị. - Cả hai đều truy cập mọi mục đúng một lần, theo thứ tự.
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>.
Lỗi thường gặp
ArrayListsử dụng.add,.get(i),.size()— không dùng[].- Lưu trữ đối tượng: hãy dùng
ArrayList<Integer>, không dùngArrayList<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.
Bây giờ bạn thử
- Mỗi nhiệm vụ điền sẵn khung lớp — viết mã của bạn bên trong main, hoặc hoàn thành phương thức được hiển thị.
- Nhấn Chạy để biên dịch và chạy, sau đó Kiểm tra câu trả lời.
- Mã của bạn được biên dịch và chạy trên máy chủ, vì vậy ngay cả lần chạy đầu tiên cũng rất nhanh.
An ArrayList grows · Một ArrayList có thể mở rộng kích thước
Unlike an array, an ArrayList changes size as you add/remove. · Khác với mảng thông thường, mộtArrayList thay đổi kích thước khi bạn thêm/xóa phần tử.
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. · Hoàn thiện sumList(ArrayList<Integer> a) sao cho nó trả về tổng của tất cả các số trong danh sách. Danh sách rỗng có tổng là 0. Duyệt qua danh sách bằng vòng lặp.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Hoàn thiện countUp(int n) sao cho nó tạo ra một ArrayList<Integer> mới, thêm các số 1, 2, ..., n theo đúng thứ tự, và trả về nó. Nếu n là 0, hãy trả về một danh sách rỗng.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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). · Hoàn thiện doubleAt(ArrayList<Integer> a, int i). Đọc giá trị tại chỉ mục i bằng get, sau đó dùng set để lưu gấp đôi giá trị đó trở lại chỉ mục i. Không trả về gì (void).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.