ArrayList란?

ArrayList는 내부적으로 배열(Array)을 사용하여 구현된 자료구조이다.
하지만, 배열과는 다르게 크기가 가변적이며, 데이터의 추가 및 삭제 작업이 편리하게 가능하다.

배열(Array)은 크기가 고정되어 있기 때문에, 배열을 생성할 때에는 미리 배열의 크기를 정해야 한다. 따라서, 데이터의 개수가 예측되지 않거나 변경될 가능성이 있는 경우에는 배열을 사용하기 어렵다.

반면에, ArrayList는 크기가 가변적이기 때문에, 데이터의 추가 및 삭제 작업에 유연하게 대처할 수 있다. 또, ArrayList는 내부적으로 배열을 사용하여 데이터를 저장하고, 배열의 크기를 자동으로 조절한다.

따라서, ArrayList는 배열과 유사한 성격을 가지고 있지만, 배열과는 다른 자료구조이다.
ArrayList는 배열의 단점인 크기가 고정되어 있을 때의 불편함을 해결하면서,
배열의 장점인 인덱스를 사용하여 빠른 접근이 가능한 성질을 유지하는 자료구조이다.


Chat-GPT 소스코드

import java.util.ArrayList;

public class ExampleArrayList {
    public static void main(String[] args) {
        // ArrayList 생성
        ArrayList<String> arrayList = new ArrayList<>();

        // 데이터 추가
        arrayList.add("사과");
        arrayList.add("바나나");
        arrayList.add("딸기");

        // 데이터 접근
        System.out.println(arrayList.get(0)); // "사과"
        System.out.println(arrayList.get(1)); // "바나나"
        System.out.println(arrayList.get(2)); // "딸기"

        // 데이터 수정
        arrayList.set(0, "포도");
        System.out.println(arrayList.get(0)); // "포도"

        // 데이터 삭제
        arrayList.remove(2); // (2)는 인덱스값
        System.out.println(arrayList.get(2)); // IndexOutOfBoundsException 발생

        // 데이터 개수
        System.out.println(arrayList.size()); // 2
    }
}

백엔드 스쿨 강의 내 코드

// ArrayList - 1차원, 2차원
System.out.println("== ArrayList ==");
ArrayList list1 = new ArrayList(Arrays.asList(1, 2, 3));
System.out.println("list1 = " + list1);
list1.add(4);
list1.add(5);
System.out.println("list1 = " + list1);
list1.remove(2); // 인덱스 2를 제거
System.out.println("list1 = " + list1);
list1.remove(Integer.valueOf(2)); // 정수값 2를 제거
System.out.println("list1 = " + list1);

ArrayList list2d = new ArrayList();
ArrayList list1d1 = new ArrayList(Arrays.asList(1, 2, 3));
ArrayList list1d2 = new ArrayList(Arrays.asList(4, 5, 6));
list2d.add(list1d1);
list2d.add(list1d2);
System.out.println("list1d1 = " + list1d1);
System.out.println("list1d2 = " + list1d2);
System.out.println("list2d = " + list2d);

출력결과

== ArrayList ==
list1 = [1, 2, 3]
list1 = [1, 2, 3, 4, 5]
list1 = [1, 2, 4, 5]
list1 = [1, 4, 5]
list1d1 = [1, 2, 3]
list1d2 = [4, 5, 6]
list2d = [[1, 2, 3], [4, 5, 6]]
profile
I'm still hungry.

0개의 댓글