컬렉션 프레임워크
- 컬렉션(collection) : 여러 객체(데이터)를 모아 놓은 것
- 프레임워크(framework) : 표준화, 정형화된 체계적인 프로그래밍 방식
- 컬렉션 프레임워크(collection framework)
컬렉션(다수의 객체)을 다루기(저장, 삭제, 검색, 정렬 등) 위한 표준화된 프로그래밍 방식
컬렉션을 쉽고 편리하게 다룰 수 있는 다양한 클래스를 제공
java.util패키지에 포함
※객체 => 다수의 데이터 - 컬렉션 클래스(collection class)
다수의 데이터를 저장할 수 있는 클래스(ex Vector, ArrayList,HashSet)
컬렉션 프레임워크의 핵심 인터페이스
- List
순서가 있는 데이터의 집합. 데이터의 중복을 허용. ArrayList, LinkedList, Stack, Vector 등
ex) 대기자 명단 - Set
순서를 유지하지 않는 데이터의 집합. 데이터의 중복을 허용하지 않음. HashSet, TreeSet 등
ex) 정수의 집합, 소수의 집합 - Map
키(key)와 값(value)의 쌍(pair)으로 이루어진 데이터의 집합.
순서는 유지되지 않으며, 키는 중복을 허용하지 않고, 값은 중복을 허용. HashMap, TreeMap, Hashtable, Properties등
ex) 지역번호(02-서울), 아이디-패스워드
List + Set의 공통부분을 => Collection
Collection 인터페이스의 메서드
List 순서 있고, 중복 가능
Set 순서가 없고, 중복 불가능
List 순서가 없고, 중복(키는 불가능, 값은 가능)
메서드 | 설명 |
boolean add(Object o) boolean addAll(Collection c) |
지정된 객체(o) 또는 Collection(c)의 객체들을 Collection에 추가 |
void clear() | Collection의 모든 객체를 삭제 |
boolean constarins(Object o), boolean(Collection c) | 지정된 객체(o) 또는 Collection의 객체들이 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에 포함된 객체들을 삭제 |
boolean retainAll(Collection c) | 지정된 Collection에 포함된 객체만을 남기고 다른 객체들은 Collection에서 삭제. 이 작업으로 Collection에 변화가 있으면 true, 그렇지 않으면 false 반환 |
int size() : | Collection에 지정된 객체의 개수를 반환 |
Object[] toArray() | Collection에 저장된 객체를 객체배열(Object[])로 반환 |
Object[] toArray(Object[] a) | 지정된 배열에 Collection의 객체를 저장해서 반환 |
List
저장 순서 O, 중복 O
Vector 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
저장 순서 X, 중복 X
HashSet, TreeSet
Set 인터페이스 메서드는 Collection 인터페이스와 동일
메서드 | 설명 |
boolean add(Object o) | 지정된 객체(o)를 Collection에 추가 |
void clear() | Collection의 모든 객체를 삭제 |
boolean constarins(Object o) | 지정된 객체(o)가 Collection에 포함되어 있는지 확인 |
boolean equals(Object o) | 동일한 Collection인지를 비교 |
int hashCode() | Collection의 hash code를 반환 |
boolean isEmpty() | Collection이 비어있는지 확인 |
Iterator iterator() | Collection의 Iterator를 얻어 반환 |
boolean remove(Object o) | 지정된 객체를 삭제 |
int size() | Collection에 지정된 객체의 개수를 반환 |
Object[] toArray() | Collection에 저장된 객체를 객체배열(Object[])로 반환 |
Object[] toArray(Object[] a) | 지정된 배열에 Collection의 객체를 저장해서 반환 |
※집합과 관련된 메서드(Collection에 변화가 있으면 true, 아니면 false를 반환)
메서드 | 설명 |
boolean addAll(Collection c) | 지정된 Collection(c)의 객체들을 Collection에 추가(합집합) |
boolean constrainsAll(Collection c) | 지정된 Collection의 객체들이 Collection에 포함되어 있는지 확인(부분집합) |
boolean removeAll(Collection c) | 지정된 Collection에 포함된 객체들을 삭제(차집합) |
boolean retainAll(Collection c) | 지정된 Collection에 포함된 객체만들 남기고 나머지는 Collection에서 삭제(교집합) |
Map
순서 X, 중복(키X, 값O)
HashMap, TreeMap
메서드 | 설명 |
void clear() | Map의 모든 객체를 삭제 |
boolean constrainsKey(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객체를 반환 |
ArrayList
기존의 Vector를 개선한 것으로 구현원리와 기능적으로 동일
ArrayList 동기화처리가 되어 있지 않고, Vector는 동기화 처리가되어 있음
List 인터페이스를 구현하므로, 저장순서가 유지되고 중복을 허용
데이터의 저장공간으로 배열을 사용(배열 기반)
ArrayList 메서드
생성자
ArrayList() 기본생성자
ArrayList(Collection c)
ArrayList(int initialCapacity) 배열의 길이
※길이를 처음부터 넉넉히 잡아두는 것이 추후에 배열을 다시 만드는 것을 방지해 줄 수 있기 때문에 편리함
추가
boolean add(Object o)
void add(int index, Object element)
boolean addAll(Collection c)
boolean addAll(int index, Collection c)
삭제
boolean remove(Object o)
Object remove(int index)
boolean removeAll(Collection c)
void clear() 모든 객체 삭제
검색
int indexOf(obejct o)
int lastIndexOf(Object o)
boolean contains(Object o)
Object get(int index)
Object set(int index, Object element)
List subList(int fromIndex, int toIndex)
Object[] toArray()
Object[] toArray(Object[] a)
boolean isEmpty()
void trimToSize()
int size()
package chapter11;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Study03Ex1 {
static void print(ArrayList list1, ArrayList list2) {
System.out.println("list1 : " + list1);
System.out.println("list2 : " + list2);
System.out.println();
}
public static void main(String[] args) {
//기본 길이(용량, capacity)가 10인 ArrayList를 생성
ArrayList list1 = new ArrayList(10);
list1.add(0); //ArrayList에는 객체만 저장가능. 컴파일러가 기본형이 참조형으로 변환.(autoboxing)
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(0));
list1.add(new Integer(3));
//ArrayList(Collection c)
ArrayList list2 = new ArrayList(list1.subList(2, 5)); //subList 읽기 전용
print(list1, list2);
//정렬
Collections.sort(list1); //list1 정렬
Collections.sort(list2); //list2 정렬 //Collections.sort(List 1)
//Collection은 인터페이스, Collections는 유틸 클래스
print(list1, list2);
System.out.println("list1.containsAll(list2) : " + list1.containsAll(list2)); //list2의 요소들이 list1에 모두 포함되는지
list2.add("C");
list2.add("B");
list2.add(3, "A"); //특정 위치에 요소를 추가
print(list1, list2);
list2.set(3, "AA"); //특정 위치의 요소를 변경
print(list1, list2);
list1.add(0,"1");
System.out.println("indexOf = " + list1.indexOf("1")); //indexOf()는 지정된 객체의 위치(인덱스)를 알려줌
System.out.println("indexOf = " + list1.indexOf(1));
list1.remove(0); //인덱스가 1인 객체를 삭제
//list1.remove(new Integer(1)); //1을 삭제
print(list1, list2);
System.out.println("list1.retainAll(list2) : " + list1.retainAll(list2)); //list1에 list2와 겹치는 부분만 남기고 나머지는 삭제
print(list1, list2);
//list2에서 list1에 포함된 객체들을 삭제
for(int i = list2.size()-1; i>=0; i--) {
if(list1.contains(list2.get(i)))
list2.remove(i);
}
print(list1, list2);
}
}
ArrayList에 저장된 객체 삭제 과정
- 삭제할 데이터 아래의 데이터를 한 칸씩 위로 복사해서 삭제할 데이터를 덮어씀
data[n]을 지우면 data[n+1]에서 data[n]으로 복사하고 덮어씀 - 데이터가 모두 한 칸씩 이동했으므로 마지막 데이터는 null로 반환
data[size-1] = null - 데이터가 삭제되어 데이터의 개수가 줄었으므로 size의 값을 감소
size--;
※마지막 데이터를 삭제하는 경우, 1.의 과정(배열 복사) 생략
=> 데이터 이동은 부담이 많이가는 작업임
ArrayList에 저장된 첫 번째 객체부터 삭제하는 경우 => 배열 복사 발생
//list에 있는 객체를 삭제하는 반복문
for(int i = 0; i< list.size(); i++){
list.remove(i);
}
//=> 배열 복사가 일어나기 때문에 전체 객체가 삭제 안됨.
ArrayList에 저장된 마지막 객체부터 삭제하는 경우 => 배열 복사 발생 안함
for(int i = list.size()-1; i >= 0; i--){
list.remove(i);
}
//빠름