이제 배열을 사용했으니 ArrayList 를 소개하겠습니다. ArrayList 는 Java Collections Framework 의 일부이며 객체 목록을 더 유연하게 처리할 수 있는 방법을 제공합니다. 배열과 달리 ArrayList 는 크기가 동적으로 증가하거나 축소될 수 있습니다.
-
프로젝트 디렉토리에서 ArrayListDemo.java
라는 파일을 엽니다.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// 여기에 코드를 추가합니다.
}
}
맨 위에 있는 import
문을 확인하십시오. 이 문은 프로그램에서 ArrayList 클래스를 사용하려는 것을 Java 에 알려줍니다.
-
이제 String 의 ArrayList 를 만들어 보겠습니다. main
메서드 안에 이 줄을 추가합니다.
ArrayList<String> fruits = new ArrayList<>();
이것은 String 객체를 담을 수 있는 빈 ArrayList 를 생성합니다. <String>
부분은 "제네릭 (generic)"이라고 하며 ArrayList 가 포함할 요소의 유형을 지정합니다.
-
ArrayList 에 몇 가지 요소를 추가해 보겠습니다. 다음 줄을 추가합니다.
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
add()
메서드는 목록의 끝에 요소를 추가합니다.
-
이제 ArrayList 를 출력해 보겠습니다. 이 코드를 추가합니다.
System.out.println("Fruits in the list:");
for (String fruit : fruits) {
System.out.println(fruit);
}
이것은 배열에서 했던 것과 유사하게, 향상된 for 루프를 사용하여 ArrayList 를 반복합니다.
팁: 출력을 보려면 언제든지 프로그램을 컴파일하고 실행할 수 있습니다. 또는 더 많은 코드를 계속 추가하고 마지막에 모두 실행할 수 있습니다.
-
ArrayList 에는 많은 유용한 메서드가 있습니다. 몇 가지를 시도해 보겠습니다. 이 코드를 추가합니다.
System.out.println("\nNumber of fruits: " + fruits.size());
System.out.println("The second fruit is: " + fruits.get(1));
size()
는 ArrayList 의 요소 수를 반환하고, get(index)
는 지정된 인덱스의 요소를 검색합니다.
-
set()
메서드를 사용하여 ArrayList 의 요소를 바꿀 수도 있습니다. 이 코드를 추가합니다.
// Before: [Apple, Banana, Cherry]
fruits.set(1, "Blueberry"); // Replaces "Banana" with "Blueberry"
System.out.println("\nAfter replacing the second fruit:");
System.out.println(fruits); // [Apple, Blueberry, Cherry]
set(index, element)
는 지정된 인덱스의 요소를 새 요소로 바꿉니다. ArrayList 크기는 동일하게 유지됩니다.
-
배열과 달리 ArrayList 는 add(index, element)
메서드를 사용하여 모든 위치에 요소를 삽입할 수 있습니다. 이것은 앞서 본 set()
과 다릅니다. add()
가 어떻게 작동하는지 살펴보겠습니다.
// Before: [Apple, Blueberry, Cherry]
fruits.add(1, "Blackberry");
System.out.println("\nAfter inserting Blackberry at index 1:");
System.out.println(fruits);
// After: [Apple, Blackberry, Blueberry, Cherry]
무슨 일이 일어났는지 이해해 봅시다.
add(1, "Blackberry")
는 "Blackberry"를 인덱스 1 에 삽입합니다.
- 인덱스 1 이상 (Blueberry, Cherry) 의 기존 요소는 자동으로 한 위치 오른쪽으로 이동합니다.
- ArrayList 크기가 1 증가합니다.
- 이것은 크기를 이동하거나 변경하지 않고 기존 요소를 바꾸는
set()
과 다릅니다.
차이점을 시각화하기 위해:
// Using add(index, element) - inserts and shifts
fruits.add(1, "Blackberry"); // [Apple, Blackberry, Blueberry, Cherry]
// Using set(index, element) - replaces without shifting
fruits.set(1, "Blackberry"); // [Apple, Blackberry, Cherry]
-
ArrayList 에서 요소를 제거할 수도 있습니다. 이 코드를 추가합니다.
fruits.remove("Cherry");
System.out.println("\nAfter removing Cherry:");
System.out.println(fruits);
이것은 ArrayList 에서 "Cherry"의 첫 번째 발생을 제거합니다. 요소가 제거되면 후속 요소가 갭을 채우기 위해 왼쪽으로 이동합니다.
-
마지막으로 특정 요소가 ArrayList 에 있는지 확인해 보겠습니다.
System.out.println("\nDoes the list contain Apple? " + fruits.contains("Apple"));
System.out.println("Does the list contain Cherry? " + fruits.contains("Cherry"));
contains()
메서드는 ArrayList 에 특정 요소가 포함되어 있는지 확인하고 부울 값을 반환합니다.
-
파일을 저장한 다음 프로그램을 컴파일하고 실행합니다.
javac ~/project/ArrayListDemo.java
java -cp ~/project ArrayListDemo
다음과 유사한 출력을 볼 수 있습니다.
Fruits in the list:
Apple
Banana
Cherry
Number of fruits: 3
The second fruit is: Banana
After replacing the second fruit:
[Apple, Blueberry, Cherry]
After inserting Blackberry at index 1:
[Apple, Blackberry, Blueberry, Cherry]
After removing Cherry:
[Apple, Blackberry, Blueberry]
Does the list contain Apple? true
Does the list contain Cherry? false
축하합니다! 이제 ArrayList 를 생성하고, 요소를 추가 및 제거하고, 인덱스로 요소에 접근하고, 다양한 ArrayList 메서드를 사용했습니다. 요소를 삽입하고 이동하는 add()
와 요소를 바꾸는 set()
과 같은 작업 간의 중요한 차이점을 배웠습니다. ArrayList 는 필요에 따라 증가하고 축소할 수 있으므로 배열보다 더 많은 유연성을 제공합니다. 이것은 작업할 요소 수를 미리 알 수 없는 경우 매우 유용합니다.