Java 기초 (컬렉션 - List(ArrayList)

최병현·2026년 1월 10일

Java

목록 보기
32/38

이 내용은 Backend / Java(OOP & Collection Framework) 영역에서 “여러 개의 데이터를 순서대로 관리”할 때 가장 많이 쓰는 구조다. List는 순서(인덱스)가 있고, 중복을 허용하며, 크기가 동적으로 늘어나는 자료구조다.


1) ArrayList 핵심 특징

  • Ordered: 입력한 순서대로 저장되고, 인덱스(0부터)로 접근한다.
  • Allow duplicates: 같은 값("python")이 여러 번 들어갈 수 있다.
  • Dynamic size: 배열처럼 크기를 미리 정하지 않아도 add()로 자동 확장된다.
  • Generic: ArrayList<String> 처럼 타입을 고정해 안전하게 사용한다.

2) add / add(index, value) / size

add(value)는 맨 뒤에 추가한다. add(index, value)는 해당 위치에 끼워 넣으며, 그 뒤 요소들은 인덱스가 한 칸씩 밀린다. size()는 현재 요소 개수다.

ArrayList<String> list = new ArrayList<>();

list.add("java");
list.add("python");
list.add("C");
list.add("python"); // duplicate allowed

System.out.println(list); // [java, python, C, python]

list.add("html"); // add to end
System.out.println(list); // [java, python, C, python, html]

list.add(1, "css"); // insert at index 1
System.out.println(list); // [java, css, python, C, python, html]

System.out.println("size: " + list.size()); // 6

3) get / indexOf

get(index)는 인덱스로 값을 꺼낸다. indexOf(value)는 “처음 발견된” 인덱스를 반환한다. 못 찾으면 -1이다.

String str = list.get(1);
System.out.println(str); // css

int index = list.indexOf("css");
System.out.println(index); // 1

System.out.println(list.indexOf("react")); // -1

4) contains / containsAll

contains는 단일 요소 포함 여부, containsAll은 “주어진 컬렉션의 모든 요소”가 들어있는지 확인한다.

ArrayList<String> tempList = new ArrayList<>();
tempList.add("python");
tempList.add("java");

System.out.println(list.contains("js"));    // false
System.out.println(list.contains("react")); // false

System.out.println(list.containsAll(tempList)); // true/false (현재 list 상태에 따라)
tempList.add("node");
System.out.println(list.containsAll(tempList)); // node가 없으면 false

5) addAll / remove / removeAll / retainAll

5-1) addAll

addAll은 다른 리스트의 요소들을 통째로 이어 붙인다.

list.addAll(tempList);
System.out.println(list); // list 뒤에 [python, java, node]가 붙음

5-2) remove("python") 주의점

remove("python")은 “첫 번째로 만나는 python 1개만” 삭제한다. 중복이 여러 개면 한 번 호출로는 하나만 지워진다.

list.remove("python"); // only first match removed
System.out.println(list);

5-3) removeAll(tempList)

removeAll은 tempList에 포함된 요소들을 list에서 “전부 제거”한다. 중복으로 여러 개 들어있어도 전부 빠진다.

list.removeAll(tempList);
System.out.println(list);

5-4) retainAll(tempList)

retainAll은 반대로 “tempList에 있는 것만 남기고 나머지를 전부 삭제”한다. 즉 교집합(intersection)만 남기는 동작이다.

list.retainAll(tempList);
System.out.println(list);
System.out.println(list.isEmpty()); // 비었는지 확인

6) Arrays.asList() (배열 → 리스트) 핵심 포인트

Arrays.asList()는 배열을 List로 “보여주는 뷰(view)”에 가깝다. 중요: 이 List는 크기 변경(add/remove)이 안 된다. (UnsupportedOperationException 발생) 대신 get/set은 가능하다.

List<String> asList = Arrays.asList(new String[] {"java", "1", "2"});
System.out.println(asList); // [java, 1, 2]

// ok
System.out.println(asList.get(0));
asList.set(0, "JAVA");

// not ok (runtime error)
// asList.add("x");
// asList.remove(0);

크기까지 자유롭게 바꾸고 싶으면 이렇게 “새 ArrayList로 복사”해서 써야 한다.

List<String> modifiable = new ArrayList<>(Arrays.asList("java", "1", "2"));
modifiable.add("x"); // ok

7) 반복문(for / enhanced for)

List는 인덱스 기반 반복(for)도 가능하고, 요소 기반 반복(enhanced for)도 가능하다.

for (int i = 0; i < asList.size(); i++) {
    System.out.println(asList.get(i));
}

for (String s : asList) {
    System.out.println(s);
}

8) 객체 배열 → List로 변환 후 조건 검색

Student[] 배열을 Arrays.asList(students)로 List로 바꾼 다음, 조건(예: studentCode)으로 원하는 학생을 찾는 흐름이다. 이건 실무에서 “DB에서 가져온 리스트를 조건으로 필터링”하는 사고방식과 동일하다.

Student student1 = new Student("gildong");
Student student2 = new Student("gilseo");
Student student3 = new Student("gilnam");
Student student4 = new Student("gilbook");
Student student5 = new Student("giljoong");

Student[] students = {student1, student2, student3, student4, student5};

List<Student> studentList = Arrays.asList(students);

for (Student student : studentList) {
    if (student.getStudentCode() == 20260002) {
        System.out.println(student.getName());
    }
}

9) 실무에서 자주 나오는 포인트

  • 중복이 싫으면 List 말고 Set(HashSet)을 쓴다. (순서가 필요하면 LinkedHashSet)
  • 검색이 많으면 List는 O(n)이라 느릴 수 있다 → key 기반이면 Map(HashMap) 고려
  • Arrays.asList는 add/remove 불가
  • remove 오버로딩 주의: Integer 리스트에서 remove(1)은 index 삭제인지 값 삭제인지 헷갈릴 수 있다

정리

  • ArrayList는 “순서 + 중복 + 동적 크기”가 핵심
  • contains/containsAll, removeAll/retainAll은 컬렉션 조작에서 자주 쓰는 조합
  • Arrays.asList는 크기 변경 불가 → 변경 필요하면 new ArrayList로 복사
  • 객체(List<Student>)도 동일한 방식으로 반복/검색/필터링 가능
// (전체 예시) 핵심만 모아둔 실행 흐름 샘플

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        list.add("java");
        list.add("python");
        list.add("C");
        list.add("python");

        System.out.println(list);

        list.add("html");
        System.out.println(list);

        list.add(1, "css");
        System.out.println(list);

        System.out.println("크기: " + list.size());

        String str = list.get(1);
        System.out.println(str);

        int index = list.indexOf("css");
        System.out.println(index);

        ArrayList<String> tempList = new ArrayList<>();
        tempList.add("python");
        tempList.add("java");

        System.out.println(list.contains("js"));
        System.out.println(list.contains("react"));

        System.out.println(list.containsAll(tempList));
        tempList.add("node");
        System.out.println(list.containsAll(tempList));

        list.addAll(tempList);
        System.out.println(list);

        list.remove("python"); // removes first match only
        System.out.println(list);

        list.removeAll(tempList); // removes all elements that exist in tempList
        System.out.println(list);

        list.retainAll(tempList); // keeps only elements that exist in tempList
        System.out.println(list);

        System.out.println(list.isEmpty());

        list.addAll(tempList);
        System.out.println(list.isEmpty());
        System.out.println();

        List<String> asList = Arrays.asList(new String[]{"java", "1", "2"});
        System.out.println(asList);

        for (int i = 0; i < asList.size(); i++) {
            System.out.println(asList.get(i));
        }

        for (String str2 : asList) {
            System.out.println(str2);
        }

        Student student1 = new Student("gildong");
        Student student2 = new Student("gilseo");
        Student student3 = new Student("gilnam");
        Student student4 = new Student("gilbook");
        Student student5 = new Student("giljoong");

        Student[] students = {student1, student2, student3, student4, student5};
        List<Student> studentList = Arrays.asList(students);

        for (Student student : studentList) {
            if (student.getStudentCode() == 20260002) {
                System.out.println(student.getName());
            }
        }
    }
}
profile
No Pain No Gain

0개의 댓글