-
02. Array 활용멋사 부트캠프/자료구조 2025. 3. 19. 17:58
1. Arrays vs ArrayList 비교표
구분 Arrays (배열) ArrayList (동적 배열) 크기 변경 ❌ 불가능 (고정 크기) ✅ 가능 (자동 조정) 데이터 타입 기본형(Primitive) & 객체 가능 객체(Reference type)만 가능 속도 ✅ 빠름 (메모리 연속 할당) ❌ 상대적으로 느림 (배열 복사 필요) 제네릭 지원 ❌ 미지원 ✅ 지원 (ArrayList<Integer> 등) 데이터 추가/삭제 ❌ 불가능 (new로 새 배열 생성 필요) ✅ add(), remove() 사용 가능 인덱스로 접근 ✅ arr[i] ✅ list.get(i) 정렬 및 변환 Arrays.sort() 지원 Collections.sort() 사용 구현 방식 Java 기본 자료구조 List 인터페이스의 구현체 대표적인 메서드 Arrays.sort(), Arrays.binarySearch() add(), remove(), size(), get() 대표적인 구현체 int[], String[] 등 new ArrayList<>() 2. ArrayList 활용하여 연결리스트 구현해보기
선언 : ArrayList<Integer> list = new ArrayList<>();
class Node { int data; int next; // 다음 노드의 인덱스를 저장 (ArrayList의 인덱스 기반) Node(int data, int next) { this.data = data; this.next = next; } } class ArrayListLinkedList { private ArrayList<Node> list; private int head; // 첫 번째 노드의 인덱스 public ArrayListLinkedList() { list = new ArrayList<>(); head = -1; } // 맨 끝에 노드 추가 public void add(int data) { if (head == -1) { // 첫 번째 노드 추가 head = 0; list.add(new Node(data, -1)); } else { int index = list.size(); // 새 노드의 인덱스 list.add(new Node(data, -1)); // 새 노드 추가 // 마지막 노드의 next를 새 노드로 변경 list.get(list.size() - 2).next = index; } } // 연결 리스트 출력 public void printList() { int index = head; while (index != -1) { System.out.print(list.get(index).data + " -> "); index = list.get(index).next; } System.out.println("null"); } } public class Main { public static void main(String[] args) { ArrayListLinkedList linkedList = new ArrayListLinkedList(); linkedList.add(10); linkedList.add(20); linkedList.add(30); linkedList.printList(); // 10 -> 20 -> 30 -> null } }
'멋사 부트캠프 > 자료구조' 카테고리의 다른 글
07. 그래프(Graph) (0) 2025.05.15 05. 큐(Queue) (0) 2025.05.15 04. Stack (2) 2025.05.04 03. 연결리스트 (1) 2025.04.17 01. 자료구조 요약 정리 (0) 2025.03.19