Chapter 1: Collections Framework
Collection 개요
Collection은 여러 개의 객체를 하나의 단위로 관리할 수 있도록 하는 자료구조입니다. Java의 Collection은 java.util 패키지에 포함되어 있으며, 다양한 자료구조를 제공합니다.
Java Collections Framework
Java Collections Framework는 자료구조와 알고리즘을 제공하는 표준화된 API입니다. 주요 인터페이스로는 Collection, List, Set, Map 등이 있습니다.
Collection 클래스의 저장 구조
- List: 순서가 있는 데이터 저장 (예: ArrayList, LinkedList)
- Set: 중복을 허용하지 않는 데이터 저장 (예: HashSet, TreeSet)
- Map: 키-값 쌍으로 데이터 저장 (예: HashMap, TreeMap)
Java Collections Framework 구성
- Collection 인터페이스: List, Set, Queue 인터페이스 포함
- Map 인터페이스: HashMap, TreeMap 등 포함
Collection 인터페이스
Collection 인터페이스는 모든 컬렉션이 구현해야 하는 메서드를 정의합니다.
Collection 인터페이스의 주요 메소드
Collection<String> collection = new ArrayList<>();
collection.add("Java");
collection.remove("Java");
collection.size();
collection.clear();
Chapter 2: Iterator, Comparable, Comparator
Iterable과 Iterator
Iterable 인터페이스는 for-each 문을 사용할 수 있도록 합니다.
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Comparable
객체의 기본 정렬 방법을 정의합니다.
class Person implements Comparable<Person> {
String name;
int age;
public int compareTo(Person other) {
return this.age - other.age;
}
}
Comparator
사용자가 정의한 기준으로 정렬할 수 있습니다.
class NameComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
}
Lab 14-1: Collection 인터페이스를 구현하는 클래스 구현
class MyCollection<T> implements Collection<T> {
private List<T> list = new ArrayList<>();
public boolean add(T item) { return list.add(item); }
public int size() { return list.size(); }
public void clear() { list.clear(); }
public Iterator<T> iterator() { return list.iterator(); }
// 기타 메소드 생략
}
Chapter 3: List
List 인터페이스
- 요소의 순서를 유지하며 중복 저장 가능
- 주요 구현 클래스: ArrayList, LinkedList, Vector, Stack
ArrayList
배열 기반 동적 리스트로, 조회 속도가 빠릅니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 1. 요소 추가
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add(1, "Orange"); // 특정 위치 삽입
// 2. 요소 삭제
list.remove("Banana"); // 값으로 삭제
list.remove(1); // 인덱스로 삭제
// 3. 요소 가져오기
System.out.println("첫 번째 요소: " + list.get(0));
// 4. 요소 포함 여부
System.out.println("Cherry 포함? " + list.contains("Cherry"));
// 5. 리스트 크기 확인
System.out.println("리스트 크기: " + list.size());
// 6. 리스트 순회
for (String fruit : list) {
System.out.println(fruit);
}
// 7. 리스트 초기화
list.clear();
System.out.println("리스트 비었나? " + list.isEmpty());
}
}
LinkedList
노드 기반 리스트로, 삽입/삭제 속도가 빠릅니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
// 1. 요소 추가
list.add("Apple");
list.addFirst("Orange"); // 맨 앞 추가
list.addLast("Grape"); // 맨 뒤 추가
// 2. 요소 삭제
list.removeFirst(); // 첫 번째 요소 삭제
list.removeLast(); // 마지막 요소 삭제
list.remove("Apple"); // 특정 값 삭제
// 3. 요소 가져오기
list.add("Banana");
list.add("Cherry");
System.out.println("첫 번째 요소: " + list.getFirst());
System.out.println("마지막 요소: " + list.getLast());
// 4. 리스트 크기 확인
System.out.println("리스트 크기: " + list.size());
// 5. 리스트 순회
for (String fruit : list) {
System.out.println(fruit);
}
}
}
Queue
FIFO(First-In-First-Out) 방식의 데이터 구조
import java.util.*;
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
// 1. 요소 추가
queue.offer(1);
queue.offer(2);
queue.offer(3);
// 2. 첫 번째 요소 확인
System.out.println("첫 번째 요소: " + queue.peek());
// 3. 요소 제거
System.out.println("제거된 요소: " + queue.poll());
// 4. 큐 크기 확인
System.out.println("큐 크기: " + queue.size());
// 5. 큐 순회
for (int num : queue) {
System.out.println(num);
}
}
}
Vector
동기화된 리스트로, 멀티스레드 환경에서 사용됩니다.
Vector<String> vector = new Vector<>();
vector.add("C++");
Stack
LIFO(Last-In-First-Out) 방식의 데이터 구조
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.pop();
Chapter 4: Set
Set 인터페이스
중복을 허용하지 않는 컬렉션
HashSet
해시 기반의 Set으로, 빠른 검색 속도를 제공합니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
// 1. 요소 추가
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // 중복 무시됨
// 2. 요소 삭제
set.remove("Banana");
// 3. 요소 포함 여부
System.out.println("Cherry 포함? " + set.contains("Cherry"));
// 4. 집합 크기 확인
System.out.println("집합 크기: " + set.size());
// 5. 집합 순회
for (String fruit : set) {
System.out.println(fruit);
}
// 6. 집합 초기화
set.clear();
System.out.println("집합 비었나? " + set.isEmpty());
}
}
TreeSet
정렬된 Set으로, Comparable을 구현한 객체를 자동 정렬합니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
// 1. 요소 추가
set.add(5);
set.add(1);
set.add(3);
// 2. 자동 정렬 확인
for (int num : set) {
System.out.println(num); // 1, 3, 5 (오름차순 정렬됨)
}
// 3. 최소값 & 최대값 찾기
System.out.println("최소값: " + ((TreeSet<Integer>) set).first());
System.out.println("최대값: " + ((TreeSet<Integer>) set).last());
// 4. 특정 값 삭제
set.remove(3);
System.out.println("3 삭제 후: " + set);
}
}
Chapter 5: Map
Map 인터페이스
키-값 쌍을 저장하는 자료구조
HashMap
해시 기반의 Map 구현
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
// 1. 요소 추가
map.put("Apple", 100);
map.put("Banana", 200);
map.put("Cherry", 300);
// 2. 값 가져오기
System.out.println("Apple 가격: " + map.get("Apple"));
// 3. 특정 키 포함 여부 확인
System.out.println("Banana 포함? " + map.containsKey("Banana"));
// 4. 요소 삭제
map.remove("Banana");
// 5. 전체 출력
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
HashTable
동기화된 해시 테이블 구조
Hashtable<String, Integer> table = new Hashtable<>();
table.put("B", 2);
TreeMap
정렬된 Map 구조
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<>();
// 1. 요소 추가
map.put(2, "Banana");
map.put(1, "Apple");
map.put(3, "Cherry");
// 2. 자동 정렬 확인
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Collections 클래스
컬렉션 관련 유틸리티 메소드를 제공합니다.
Collection 동기화
멀티스레드 환경에서 컬렉션을 안전하게 동기화하는 방법
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
Readonly Collection
읽기 전용 컬렉션 생성
List<String> readOnlyList = Collections.unmodifiableList(new ArrayList<>());
Checked Collection
타입 안정성이 보장된 컬렉션 생성
List rawList = new ArrayList();
List<String> checkedList = Collections.checkedList(rawList, String.class);