이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
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;.
English
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.
English
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]
}
}
English
The methods you need
list.size()— how many items are in the list.list.add(x)— putxat the end of the list.list.add(i, x)puts it at positioniinstead, shifting later items right.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.
English
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]
}
}
English
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.
English
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
}
}
English
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.
English
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
}
}
English
Common mistakes
ArrayListuses.add,.get(i),.size()— not[].- Store objects: use
ArrayList<Integer>, notArrayList<int>.
English
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Use Check answer to compile your code with the supplied tests and view the results. Keep the class and method interfaces shown in the starter.
- Your code compiles and runs on the server, so even the first run is fast.
탐색하기
ArrayList은 커집니다
배열과 달리 ArrayList은 add/remove를 할 때 크기가 변합니다.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
sumList(ArrayList<Integer> a)를 완성하여 목록 내 모든 숫자의 총합을 반환하게 하세요. 빈 목록의 총합은 0입니다. 루프로 순회하세요.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
countUp(int n)를 완성하세요. 새로운 ArrayList<Integer>를 만들어 숫자 1, 2, ..., n를 순서대로 추가하고 반환합니다. n가 0라면 빈 목록을 반환하세요.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
doubleAt(ArrayList<Integer> a, int i)를 완성하세요. 인덱스 i의 값을 get로 읽고, set를 사용하여 그 값의 두 배를 인덱스 i에 다시 저장하세요. 아무것도 반환하지 않습니다(void).
출력을 보려면 '실행'을 클릭하세요.