| 인터페이스 | 순서 | 중복 | 구현된 클래스 |
|---|---|---|---|
| Collection | x | o | (사실 개념만 있음→ 순서가 없으면 중복도 없어야하는데 이건 불가능해서 개념만 존재함) |
| Set | x | x | HashSet(넣었던 순서를 보장하지 못한다), TreeSet(자동적으로 정렬이 된다. 오름차순) |
| List | o | o | ArrayList(삽입,삭제가 빈번하면 효율이 떨어진다),LinkedList(포인터라고 생각하면 된다) |
| 메서드 | 설명 |
|---|---|
| boolean add(E e) | 컬렉션에 엘리먼트를 추가합니다. 추가되지 않을 때 false를 반환합니다. |
| void clear() | 컬렉션의 모든 엘리먼트를 삭제합니다. |
| boolean contains(Object o) | 컬렉션이 주어진 객체를 포함하면 true를 반환합니다. |
| boolean isEmpty() | 컬렉션이 비어있으면 true를 반환합니다. |
| Iterator iterator() | 이 컬렉션의 iterator 객체를 반환합니다. |
| boolean
remove(Object o) | 주어진 엘리먼트 객체를 제거합니다. |
| Object[] toArray() | 이 컬렉션의 모든 엘리먼트들을 배열로 반환합니다. |
| T[] toArray(T[] a) | 컬렉션의 모든 엘리먼트들을 주어진 타입의 배열로 반환합니다. |
Set 인터페이스는 중복된 데이터를 저장할 수 없는 컬렉션입니다. 즉, 동일한 객체를 여러 번 추가하려 해도 하나만 저장됩니다.
또한, SortedSet 인터페이스는 저장된 객체를 오름차순으로 정렬하여 관리합니다. 이를 구현한 클래스에는 TreeSet과 ConcurrentSkipListSet이 있습니다.
| 메서드 | 설명 |
|---|---|
boolean add(E e) | Set에 요소를 추가. 중복된 값이면 false 반환 |
void clear() | Set의 모든 요소 삭제 |
boolean contains(Object o) | 특정 객체 포함 여부 확인 (true 반환) |
boolean isEmpty() | Set이 비어있는지 확인 (true 반환) |
Iterator<E> iterator() | Set의 iterator 객체 반환 |
boolean remove(Object o) | 특정 객체 제거 |
int size() | Set의 요소 개수 반환 |
Object[] toArray() | Set의 모든 요소를 배열로 반환 |
<T> T[] toArray(T[] a) | Set의 모든 요소를 지정된 타입의 배열로 변환 |
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // 중복 추가, 저장되지 않음
set.add("cherry");
System.out.println("Set 데이터: " + set); // 중복 제거 후 출력
set.remove("banana");
System.out.println("banana 제거 후 Set: " + set);
System.out.println("Set에 cherry 포함? " + set.contains("cherry"));
System.out.println("Set 크기: " + set.size());
set.clear();
System.out.println("clear() 후 Set이 비었는가? " + set.isEmpty());
}
}
HashSet은 중복된 데이터를 허용하지 않는 Set 컬렉션이며, 해시 테이블을 사용해 데이터를 저장합니다.
해시 테이블은 Key-Value 매핑을 통해 데이터를 관리하며, HashSet은 내부적으로 Key만 관리합니다.
| 메서드 | 설명 |
|---|---|
boolean add(E e) | 요소 추가. 중복된 값이면 false 반환 |
boolean contains(Object o) | 특정 요소 포함 여부 확인 |
boolean isEmpty() | HashSet이 비어있는지 확인 |
boolean remove(Object o) | 특정 요소 제거 |
void clear() | 모든 요소 삭제 |
int size() | 현재 저장된 요소 개수 반환 |
import java.util.*;
public class HashSetExample {
public static void main(String args[]) {
Set<Object> set = new HashSet<>();
set.add("three");
set.add("one");
set.add("two");
set.add("four");
set.add("five");
set.add(4); // Integer 객체 추가
boolean isAdded1 = set.add("five"); // 중복 추가 (저장 안됨)
boolean isAdded2 = set.add(new String("five")); // 같은 값이지만 새로운 객체이므로 저장 가능
System.out.println(set); // 저장된 요소 출력
System.out.println("isAdded1: " + isAdded1); // false (중복)
System.out.println("isAdded2: " + isAdded2); // false (동일한 문자열)
System.out.println("Set 크기: " + set.size());
set.remove("two"); // 특정 요소 삭제
System.out.println("two 제거 후 Set: " + set);
set.clear(); // 모든 요소 삭제
System.out.println("clear() 후 Set: " + set);
if (set.isEmpty()) {
System.out.println("Set is Empty");
}
}
}
TreeSet은 SortedSet을 구현한 클래스로, 데이터를 자동 정렬하여 저장하는 특징이 있습니다.
즉, 오름차순으로 정렬된 상태를 유지하며 데이터가 삽입됩니다.
| 메서드 | 설명 |
|---|---|
boolean add(E e) | 요소 추가 |
boolean contains(Object o) | 특정 요소 포함 여부 확인 |
E first() | 가장 작은 요소 반환 |
E last() | 가장 큰 요소 반환 |
E higher(E e) | 지정된 값보다 큰 요소 반환 |
E lower(E e) | 지정된 값보다 작은 요소 반환 |
boolean remove(Object o) | 특정 요소 제거 |
void clear() | 모든 요소 삭제 |
int size() | 요소 개수 반환 |
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<>();
ts.add("hello");
ts.add("java");
ts.add("aaa");
ts.add("computer");
// 자동 정렬된 데이터 출력
for (String str : ts) {
System.out.print(str + "\t");
}
System.out.println("\n첫 번째 요소: " + ts.first());
System.out.println("마지막 요소: " + ts.last());
System.out.println("hello보다 큰 값: " + ts.higher("hello"));
}
}
true)true 반환)1은 찾지 못함)true 반환)import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add("one");
list.add("second");
list.add("3rd");
list.add(4);
list.add(5.0f);
list.add("second"); // 같은 값 저장 가능
list.add(4);
list.add("SECOND");
System.out.println(list); // 전체 출력
list.remove(0); // 첫 번째 요소 삭제
System.out.println(list);
Object o = list.get(1); // 인덱스 1의 요소 가져오기
System.out.println(o);
int index = list.indexOf("second"); // 특정 값 위치 찾기
System.out.println("second 위치: " + index);
list.clear(); // 모든 요소 삭제
if (list.isEmpty()) {
System.out.println("list is Empty");
}
}
}
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("hello");
list.add("java");
list.add("banana");
list.addFirst("apple"); // 맨 앞 추가
list.addLast("zoo"); // 맨 뒤 추가
System.out.println("초기 리스트: " + list);
list.remove(); // 첫 번째 요소 삭제
System.out.println("remove() 후 리스트: " + list);
list.remove(2); // 인덱스 2 삭제
System.out.println("remove(2) 후 리스트: " + list);
list.set(1, "new_element"); // 인덱스 1 변경
System.out.println("set() 후 리스트: " + list);
String peeked = list.peek(); // 첫 번째 요소 조회
System.out.println("peek() 결과: " + peeked);
System.out.println("peek() 후 리스트: " + list);
String polled = list.poll(); // 첫 번째 요소 조회 후 삭제
System.out.println("poll() 결과: " + polled);
System.out.println("poll() 후 리스트: " + list);
}
}
Map은 Key-Value 쌍으로 데이터를 저장하는 컬렉션입니다.| 메서드 | 설명 |
|---|---|
void clear() | 모든 요소 삭제 |
boolean containsKey(Object key) | 특정 키가 존재하면 true 반환 |
boolean containsValue(Object value) | 특정 값이 존재하면 true 반환 |
Set<Map.Entry<K,V>> entrySet() | Map의 모든 키-값 쌍을 Set으로 반환 |
V get(Object key) | 키에 해당하는 값 반환 (null 가능) |
boolean isEmpty() | Map이 비어있는지 확인 |
Set<K> keySet() | 모든 키를 Set으로 반환 |
V put(K key, V value) | 키-값 저장 |
void putAll(Map m) | 다른 Map의 데이터를 현재 Map에 복사 |
V remove(Object key) | 특정 키의 요소 제거 |
int size() | 요소 개수 반환 |
Collection<V> values() | 모든 값을 Collection으로 반환 |
HashMap은 빠른 검색과 저장이 가능한 Map 컬렉션입니다.
순서를 유지하지 않지만 keySet() 또는 entrySet()을 사용하여 반복 처리가 가능합니다.
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Object> maps = new HashMap<>();
maps.put("name", "홍길동");
maps.put("hiredate", new Date());
maps.put("salary", 20000);
System.out.println("전체 Map: " + maps);
System.out.println("* key를 이용한 값 조회");
System.out.println("hiredate: " + maps.get("hiredate"));
System.out.println("salary: " + maps.get("salary"));
System.out.println("name: " + maps.get("name"));
System.out.println("* entrySet을 이용한 데이터 출력");
for (Map.Entry<String, Object> entry : maps.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("* keySet을 이용한 데이터 출력");
for (String key : maps.keySet()) {
System.out.println(key + " :: " + maps.get(key));
}
}
}
TreeMap은 오름차순 정렬을 지원하는 Map 컬렉션입니다.
데이터를 저장할 때 Key 기준으로 자동 정렬됩니다.
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
Map<String, Integer> accounts = new TreeMap<>();
accounts.put("홍길동", 10000);
accounts.put("이순신", 50000);
accounts.put("정준수", 90000);
accounts.put("허현수", 70000);
System.out.println("전체 Map: " + accounts);
System.out.println("* key를 이용한 값 조회");
System.out.println("허현수: " + accounts.get("허현수"));
System.out.println("* entrySet을 이용한 데이터 출력");
for (Map.Entry<String, Integer> entry : accounts.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("* keySet을 이용한 데이터 출력");
for (String key : accounts.keySet()) {
System.out.println(key + " :: " + accounts.get(key));
}
}
}
Iterator는 컬렉션에 저장된 요소를 하나씩 검색하는 인터페이스입니다.| 메서드 | 설명 |
|---|---|
boolean hasNext() | 다음 요소가 있으면 true 반환 |
E next() | 다음 요소 반환 |
void remove() | Iterator에서 반환된 요소 삭제 |
import java.util.*;
public class IteratorExample {
public static void main(String args[]) {
Set<Object> set = new HashSet<>();
set.add("three");
set.add("two");
set.add("four");
set.add("five");
set.add(4);
Iterator<Object> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Properties 클래스는 설정 파일 (properties 파일)을 읽어 맵 객체로 변환하는 클래스입니다.
실제 사용 빈도는 낮지만 설정 값을 관리할 때 유용합니다.
database.properties)driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
username=scott
password=tiger
PropertiesExample.java)import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.load(new FileReader("database.properties"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println("Driver: " + prop.getProperty("driver"));
System.out.println("URL: " + prop.getProperty("url"));
}
}
객체를 비교하는 방법은 크게 두 가지로 나뉩니다:
equals(), hashCode())Set 컬렉션에서 중복 방지에 사용됨Comparable, Comparator)TreeSet, Collections.sort() 등에 사용객체를 비교할 때 == 연산자를 사용하면 참조값(메모리 주소)를 비교하기 때문에 내용 비교가 불가능합니다.
객체의 내용을 비교하려면 equals()와 hashCode() 메서드를 재정의해야 합니다.
[객체1] ──(객체의 주소값 비교)──> [객체2] (X, 서로 다른 객체)
[객체1] ──(객체의 내용 비교)──> [객체2] (O, 같은 내용이면 true)
equals() & hashCode() 활용)public class Dog { // Dog 클래스 정의
String dogId; // 개의 ID
String dogName; // 개의 이름
// 생성자: 개의 ID와 이름을 초기화
public Dog(String dogId, String dogName) {
this.dogId = dogId; // this는 현재 객체를 가리킴 (dogId 할당)
this.dogName = dogName; // this는 현재 객체를 가리킴 (dogName 할당)
}
// 객체 동등 비교를 위한 equals() 메서드 재정의
@Override
public boolean equals(Object obj) {
// 1. 객체의 주소값(참조값)이 같으면 true (같은 객체를 가리킴)
if (this == obj) return true;
// 2. 비교 대상이 null이면 false
if (obj == null) return false;
// 3. 객체 타입이 다르면 false (다른 클래스의 객체라면 비교 불가능)
if (getClass() != obj.getClass()) return false;
// 4. obj를 Dog 타입으로 변환하여 비교할 준비
Dog d = (Dog) obj;
// 5. dogId와 dogName이 모두 같다면 같은 객체로 간주
return dogId.equals(d.dogId) && dogName.equals(d.dogName);
}
// 객체의 해시 값을 반환 (HashSet 등에서 사용)
@Override
public int hashCode() {
// XOR(^) 연산을 사용하여 해시코드 생성 (dogId와 dogName을 활용)
return dogId.hashCode() ^ dogName.hashCode();
}
// 객체를 문자열로 변환하는 메서드
@Override
public String toString() {
return dogId + " : " + dogName;
}
}
Set 활용)import java.util.HashSet;
import java.util.Set;
public class ObjectEqualsExample {
public static void main(String[] args) {
Dog d1 = new Dog("1234567890", "바둑이");
Dog d2 = new Dog("1234567890", "바둑이");
System.out.println(d1.equals(d2)); // true (객체 내용 비교)
System.out.println(d1 == d2); // false (참조값 비교)
Set<Dog> set = new HashSet<>();
System.out.println("d1 저장: " + set.add(d1));
System.out.println("d2 저장: " + set.add(d2)); // false (중복 저장 X)
}
}
Comparable 사용)객체를 정렬 가능하게 하려면 Comparable 인터페이스를 구현해야 합니다.
public class Tiger implements Comparable<Tiger> {
String name;
Tiger(String name) {
this.name = name;
}
@Override
public int compareTo(Tiger obj) {
return this.name.compareTo(obj.name); // 이름 기준으로 정렬
}
}
Collections.sort() 활용)import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<Tiger> list = new ArrayList<>();
list.add(new Tiger("라이거"));
list.add(new Tiger("백호"));
list.add(new Tiger("한라산"));
list.add(new Tiger("백두"));
Collections.sort(list); // 이름 기준 정렬
for (Tiger t : list) {
System.out.println(t.name);
}
}
}
Comparable 구현)TreeSet은 삽입된 모든 객체를 정렬된 상태로 유지합니다.TreeSet에 삽입되는 객체는 Comparable을 구현해야 합니다.public class Employee implements Comparable<Employee> {
String name;
int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return name + " : " + salary;
}
@Override
public int compareTo(Employee emp) {
return this.name.compareTo(emp.name); // 이름 기준 정렬
}
}
import java.util.TreeSet;
public class ComparableExample {
public static void main(String[] args) {
TreeSet<Employee> list = new TreeSet<>();
list.add(new Employee("홍길동", 20000));
list.add(new Employee("허현정", 30000));
list.add(new Employee("허현준", 70000));
list.add(new Employee("허현수", 40000));
for (Employee e : list) {
System.out.println(e);
}
}
}
salary 기준으로 정렬compareTo()를 수정해야 합니다.public class Employee implements Comparable<Employee> {
String name;
int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return name + " : " + salary;
}
@Override
public int compareTo(Employee emp) {
return Integer.compare(this.salary, emp.salary); // 급여 기준 정렬
}
}
import java.util.TreeSet;
public class ComparableExample {
public static void main(String[] args) {
TreeSet<Employee> list = new TreeSet<>();
list.add(new Employee("홍길동", 20000));
list.add(new Employee("허현정", 30000));
list.add(new Employee("허현준", 70000));
list.add(new Employee("허현수", 40000));
for (Employee e : list) {
System.out.println(e);
}
}
}
[객체1] → [객체2] → [객체3] → [객체4] (이름 순 정렬)
[객체3] → [객체4] → [객체2] → [객체1] (급여 순 정렬)
Comparator는 기존 객체를 수정하지 않고 정렬 기준을 지정할 수 있는 인터페이스입니다.Comparable을 직접 구현하지 않은 객체도 Comparator를 사용하면 정렬 가능합니다.compare(T o1, T o2) 메서드를 재정의하여 두 객체의 크기 비교 가능Collections.sort() 또는 TreeSet 등에서 활용 가능Tiger2 클래스 정렬Comparable을 구현하지 않은 Tiger2 객체를 Comparator로 정렬하는 예제입니다.public class Tiger2 { // 일반 객체 (Comparable 미구현)
String name;
// 생성자: Tiger2 객체의 이름을 초기화
public Tiger2(String name) {
this.name = name;
}
}
Comparator 구현)import java.util.Comparator;
public class Tiger2Comparator implements Comparator<Tiger2> {
// compare() 메서드: 두 객체의 이름을 기준으로 정렬
@Override
public int compare(Tiger2 o1, Tiger2 o2) {
return o1.name.compareTo(o2.name); // 문자열 정렬 (오름차순)
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Tiger2ComparatorExample {
public static void main(String[] args) {
// Tiger2 객체 리스트 생성
List<Tiger2> list = new ArrayList<>();
list.add(new Tiger2("라이거"));
list.add(new Tiger2("백호"));
list.add(new Tiger2("한라산"));
list.add(new Tiger2("백두"));
// Comparator를 사용하여 정렬
Collections.sort(list, new Tiger2Comparator());
// 정렬된 결과 출력
for (Tiger2 t : list) {
System.out.println(t.name);
}
}
}
결과 (이름순 오름차순 정렬)
백두
백호
라이거
한라산
Employee2 객체 정렬Employee2 객체를 Comparator로 다양한 기준(이름, 급여) 정렬하는 예제입니다.public class Employee2 {
String name;
int salary;
// 기본 생성자
public Employee2() {}
// 생성자: Employee2 객체의 이름과 급여를 초기화
public Employee2(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return name + " : " + salary;
}
}
Employee2 객체를 이름순 오름차순으로 정렬하는 Comparatorimport java.util.Comparator;
public class Employee2Comparator implements Comparator<Employee2> {
@Override
public int compare(Employee2 obj1, Employee2 obj2) {
return obj1.name.compareTo(obj2.name); // 이름 기준 오름차순 정렬
}
}
Employee2 객체를 급여순 오름차순으로 정렬하는 Comparatorimport java.util.Comparator;
public class Employee2SalaryComparator implements Comparator<Employee2> {
@Override
public int compare(Employee2 obj1, Employee2 obj2) {
return obj1.salary - obj2.salary; // 급여 기준 오름차순 정렬
}
}
TreeSet을 사용하여 정렬import java.util.TreeSet;
public class Employee2ComparatorExample {
public static void main(String[] args) {
// Employee2 객체 생성
Employee2 e1 = new Employee2("홍길동", 20000);
Employee2 e2 = new Employee2("김진숙", 30000);
Employee2 e3 = new Employee2("허현정", 70000);
Employee2 e4 = new Employee2("이순신", 40000);
// 이름 기준 정렬 (Employee2Comparator 사용)
TreeSet<Employee2> nameSortedList = new TreeSet<>(new Employee2Comparator());
nameSortedList.add(e1);
nameSortedList.add(e2);
nameSortedList.add(e3);
nameSortedList.add(e4);
System.out.println("▶ 이름 기준 정렬:");
for (Employee2 e : nameSortedList) {
System.out.println(e);
}
// 급여 기준 정렬 (Employee2SalaryComparator 사용)
TreeSet<Employee2> salarySortedList = new TreeSet<>(new Employee2SalaryComparator());
salarySortedList.add(e1);
salarySortedList.add(e2);
salarySortedList.add(e3);
salarySortedList.add(e4);
System.out.println("\n▶ 급여 기준 정렬:");
for (Employee2 e : salarySortedList) {
System.out.println(e);
}
}
}
▶ 이름 기준 정렬:
김진숙 : 30000
이순신 : 40000
홍길동 : 20000
허현정 : 70000
▶ 급여 기준 정렬:
홍길동 : 20000
김진숙 : 30000
이순신 : 40000
허현정 : 70000
✅ Comparable → 클래스 내부에서 기본 정렬 방식 지정 (compareTo())
✅ Comparator → 외부에서 정렬 기준 추가 가능 (compare())
✅ Collections.sort(list, new Comparator<>()) → List 정렬 가능
✅ TreeSet<Employee>(new Comparator<>()) → TreeSet에 정렬 기준 적용 가능