ArrayList: a list that grows · ArrayList: 커지는 목록
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;.
커질 수 있는 목록
- 배열은 고정된 크기다. 한 번 만들면 길이는 변할 수 없다.
- **
ArrayList**은 프로그램 실행 중에는 늘어나거나 줄어드는 list(목록)이다. - 파일 상단에 반드시 import해야 한다:
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.
ArrayList 만들기
<...>내부에 들어갈 항목의 타입을 적어라. 이것이 AP CSA 방식이다.ArrayList<String>은 텍스트를 저장한다.ArrayList<Integer>은 정수를 저장한다.- 새 목록은 비어あり, 크기는
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.
필요한 다섯 가지 방법
list.size()— 목록에 있는 항목 수.list.add(x)—x을 목록의 끝에 추가한다.list.get(i)— 위치i에 있는 항목을 반환한다 (첫 번째 위치는 0).list.set(i, x)— 위치i의 항목을x로 교체한다.list.remove(i)— 위치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.
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. add(7)을int에 적용하고,get(0)에서 Returned한 값을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.
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>.
흔한 실수
ArrayListuses.add,.get(i),.size()— not[].- Store objects: use
ArrayList<Integer>, notArrayList<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.
이제 직접 해보기
- 각 과제는 클래스 골격을 미리 채워 놓으므로, 코드를 main 내부에 작성하거나 제시된 메서드를 완성하십시오.
- Run 버튼을 눌러 컴파일하고 실행한 후, Answer 확인 버튼을 누르세요.
- 코드는 서버에서 컴파일되고 실행되므로 첫 실행에서도 빠릅니다.
An ArrayList grows · ArrayList은 커집니다
Unlike an array, an ArrayList changes size as you add/remove. · 배열과 달리 ArrayList은 add/remove를 할 때 크기가 변합니다.
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. · sumList(ArrayList<Integer> a)를 완성하여 목록 내 모든 숫자의 총합을 반환하게 하세요. 빈 목록의 총합은 0입니다. 루프로 순회하세요.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
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. · countUp(int n)를 완성하세요. 새로운 ArrayList<Integer>를 만들어 숫자 1, 2, ..., n를 순서대로 추가하고 반환합니다. n가 0라면 빈 목록을 반환하세요.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
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). · doubleAt(ArrayList<Integer> a, int i)를 완성하세요. 인덱스 i의 값을 get로 읽고, set를 사용하여 그 값의 두 배를 인덱스 i에 다시 저장하세요. 아무것도 반환하지 않습니다(void).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.