
이 내용은 Backend / Java(OOP & Collection Framework) 영역에서 “여러 개의 데이터를 순서대로 관리”할 때 가장 많이 쓰는 구조다. List는 순서(인덱스)가 있고, 중복을 허용하며, 크기가 동적으로 늘어나는 자료구조다.
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
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
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
addAll은 다른 리스트의 요소들을 통째로 이어 붙인다.
list.addAll(tempList);
System.out.println(list); // list 뒤에 [python, java, node]가 붙음
remove("python")은 “첫 번째로 만나는 python 1개만” 삭제한다. 중복이 여러 개면 한 번 호출로는 하나만 지워진다.
list.remove("python"); // only first match removed
System.out.println(list);
removeAll은 tempList에 포함된 요소들을 list에서 “전부 제거”한다. 중복으로 여러 개 들어있어도 전부 빠진다.
list.removeAll(tempList);
System.out.println(list);
retainAll은 반대로 “tempList에 있는 것만 남기고 나머지를 전부 삭제”한다. 즉 교집합(intersection)만 남기는 동작이다.
list.retainAll(tempList);
System.out.println(list);
System.out.println(list.isEmpty()); // 비었는지 확인
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
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);
}
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());
}
}
remove(1)은 index 삭제인지 값 삭제인지 헷갈릴 수 있다// (전체 예시) 핵심만 모아둔 실행 흐름 샘플
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());
}
}
}
}