- 컬렉션 프레임워크(Collection Framework)란?
데이터 군(그룹)을 저장하는 클래스들을 표준화한 설계이다.인터페이스와 다형성을 이용한 객체지향적 설계를 통해 표준화되어 있어 사용하기 편리하고, 재사용성이 높은 코드를 작성할 수 있다는 장점을 제공한다.
- 컬렉션 프레임워크의 핵심 인터페이스
컬렉션 데이터 그룹은 크게 3가지 타입이 존재한다고 인식하여 아래와 같이 3개의 인터페이스를 정의한다.
인터페이스 | 특징 |
List | 순서 있는 데이터 집합 데이터 중복 허용 |
구현(implements 하는) 클래스: ArrayList, LinkedList, Stack, Vector 등 | |
Set | 순서 없는 데이터 집합 데이터 중복 ❌ |
구현 클래스: HashSet, TreeSet 등 | |
Map | 키(key)와 값(value)의 쌍(pair)으로 이루어진 순서 없는 데이터 집합 키 중복 ❌, 값 중복 허용 |
구현 클래스: HashMap, TreeMap, Hashtable, Properties 등 |
List와 Set을 구현한 컬렉션 클래스들은 많은 공통 부분이 있어 이런 공통 부분을 뽑아 Collection 인터페이스를 정의할 수 있었다.
위 구현 클래스를 이용해 객체를 생성하는 경우 아래 코드처럼 인터페이스를 타입으로 하는 참조형 변수에 저장할 수 있다.
new List(); 이런 거는 불가능
List listVariable = new ArrayList());
- Collection 인터페이스
Collection 인터페이스는 List와 Set의 조상이거, 다음과 같은 메서드들이 정의되어있다.
메서드 | 설명 |
boolean add(Object o) boolean addAll(Collection c) |
지정된 객체(o) 또는 Collection(c)의 객체들을 Collection에 추가 성공 시 true, 실패 시 false 반환 |
void clear() | Collection의 모든 객체를 삭제 |
boolean contains(Object o) boolean containsAll(Collection c) |
지정된 객체(o) 또는 Collection(c)의 객체들을 Collection에 포함되어 있는지 확인 |
boolean equals(Object o) | 동일한 Collection인지 비교 |
int hashCode() | Collection의 hash code 반환 |
boolean isEmpty() | Collection이 비어있는지 확인 |
Iterator iterator() | Collection의 Iterator를 얻어 반환 |
boolean remove(Object o) | 지정된 객체 삭제 |
boolean removeAll(Collection c) | 지정된 Collection에 포함된 객체들을 삭제 |
int size() | Collection에 저장된 객체의 개수 반환 |
Object[] toArray() | Collection에 저장된 객체를 객체배열(Object[])로 반환 |
Object[] toArray(Object[] a) | 지정된 배열에 Collection의 객체를 지정해서 반환 |
반환 타입이 boolean인 메서드들은 성공 시 true, 실패 시 false를 반환한다.
Collection은 인터페이스 이기 때문에 위 메서드들을 정의만 할 뿐 구현되어 있지는 않다. 메서드 구현은 구현 클래스들이 상속하여 오버라이딩을 하고 구현한다.
- List 인터페이스
List 인터페이스는 데이터의 중복을 허용하면서 저장 순서가 유지되는 컬렉션을 구현하는 데에 사용된다.
List 인터페이스를 구현한 클래스로는 ArrayList, LinkedList 등이 있으며, 이에 정의된 메서드는 다음과 같다.
메서드 | 설명 |
void add(int index, Object element) boolean addAll(int index, Collection c) |
지정된 위치(index)에 객체(element) 또는 컬렉션에 포함된 객체들을 추가 |
Object get(int index) | 지정된 위치(index)에 있는 객체를 반환 |
int indexOf(Object o) | 지정된 객체의 첫번째 위치(index)를 반환 (List의 첫번째 요소부터 순방향으로 탐색) |
int lastIndexOf(Object o) | 지정된 객체의 마지막 위치(index)를 반환 (List의 첫번째 요소부터 역방향으로 탐색) |
ListIterator listIterator() ListIterator listIterator(int index) |
List의 객체에 접근할 수 있는 ListIterator를 반환 |
Object remove(int index) | 지정된 위치(index)에 있는 객체를 삭제하고 삭제된 객체를 반환 |
Object set(int index, Object element) | 지정된 위치(index)에 객체(element)를 저장 |
void sort(Comparator c) | 지정된 비교자(comparator)로 List를 정렬 |
List subList(int fromIndex, int toIndex) | 지정된 범위(fromIndex부터 toIndex)에 있는 객체를 반환한다. |
- Set 인터페이스
Set 인터페이스는 중복을 허용하지 않고 저장 순서가 없는 컬렉션 클래스를 구현하는 데에 사용된다.
Set 인터페이스를 구현한 클래스로는 HashSet, TreeSet 등이 있다.
- Map 인터페이스
Map 인터페이스는 키(key)와 값(value)을 하나의 쌍으로 묶어서 저장하는 컬렉션 클래스를 구현하는 데에 사용된다.
키는 중복될 수 없지만 값은 중복을 허용한다.
만일 중복된 키에 값을 저장하면 기존의 값이 없어지고 새로운 값이 저장된다.
Map 인터페이스를 구현한 클래스로는 Hashtable, HashMap, LinkedHashMap, SortedMap, TreeMap 등이 있으며, 이에 정의된 메서드는 다음과 같다.
메서드 | 설명 |
void clear() | Map의 모든 객체를 삭제 |
boolean containsKey(Object key) | 지정된 key객체와 일치하는 Map의 key객체가 있는지 확인 |
boolean containsValue(Object value) | 지정된 value객체와 일치하는 Map의 value객체가 있는지 확인 |
Set entrySet() | Map에 저장되어 있는 key-value 쌍을 Map.Entry타입의 객체로 저장한 Set으로 반환 |
boolean equals(Object o) | 동일한 Map인지 비교 |
Object get(Object key) | 지정한 key객체에 대응하는 value 객체를 찾아 반환 |
int hashCode() | 해시코드 반환 |
boolean isEmpty() | Map이 비어있는지 확인 |
Set keySet() | Map에 저장된 모든 key객체를 반환 |
Object put(Object key, Object value) | Map에 저장된 value객체를 key객체에 연결(mapping)하여 저장 |
void putAll(Map t) | 지정된 Map의 모든 key-value쌍을 추가 |
Object remove(Object key) | 지정한 key객체와 일치하는 key-value객체를 삭제 |
int size() | Map에 저장된 key-value쌍의 개수를 반환 |
Collection values() | Map에 저장된 모든 value객체를 반환 |
keySet()이 Set을 반환하는 것은 키는 중복을 허용하지 않기 때문이다.
values()가 Collection을 반환하는 것은 값은 중복을 허용하기 때문이다.
- Map.Entry 인터페이스
Map.Entry 인터페이스는 Map에 저장되는 key-value쌍을 다루기 위해 정의되었으며, Map 인터페이스의 내부 인터페이스(내부 클래스처럼 인터페이스 안에 인터페이스를 정의함)이다.
Map 인터페이스를 구현하는 클래스에서는 Map.Entry 인터페이스도 구현해야한다.
Map.Entry 인터페이스에 정의된 메서드는 다음과 같다.
메서드 | 설명 |
boolean equals(Object o) | 동일한 Entry인지 비교 |
Object getKey() | Entry의 key객체 반환 |
Object getValue() | Entry의 value객체 반환 |
int hashCode() | Entry의 해시코드 반환 |
Object setValue(Object value) | Entry의 value객체를 지정된 객체로 바꿈 |
Map.Entry 인터페이스는 다음 코드와 같이 사용할 수 있다.
import java.util.HashMap;
import java.util.Map;
public class MapEntryExample {
public static void main(String[] args) {
// HashMap 생성
Map<String, Integer> myMap = new HashMap<>();
// 키-값 추가
myMap.put("One", 1);
myMap.put("Two", 2);
myMap.put("Three", 3);
// entrySet()을 이용한 Map.Entry 반복
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
참고
Java의 정석 3판 - 남궁성
기준일자: 2024년 01월 19일
정정해야할 내용이 있다면 댓글로 작성 부탁드립니다!
'Java' 카테고리의 다른 글
[Java] 문과 표현식 (3) (0) | 2024.02.20 |
---|---|
[Java] 문과 표현식 (2) (2) | 2024.02.20 |
[Java] 문과 표현식 (1) (0) | 2024.02.20 |
[Java] 변수 (0) | 2024.01.19 |
[Java] 자바, JVM, JRE, JDK (1) | 2024.01.19 |