1. set (중복을 허용하지 않는 집합)
중복을 허용하지 않으며, 순서가 중요하지 않은 데이터를 저장
| 종류 | 정렬 | 중복 허용 | 순서 유지 | 특징 |
| HashSet | X | X | X | 가장 빠름 |
| LinkedHashSet | X | X | O | 입력 순서를 유지 |
| TreeSet | 오름차순 자동 정렬 | X | X | 자동정렬 |
import java.util.*;
public class SetExample {
public static void main(String[] args) {
// 1️⃣ HashSet (중복X, 순서X)
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Cherry");
hashSet.add("Apple"); // 중복 추가 (무시됨)
System.out.println("HashSet: " + hashSet); // [Banana, Cherry, Apple] (순서 랜덤)
// 2️⃣ LinkedHashSet (중복X, 입력 순서 유지)
Set<String> linkedSet = new LinkedHashSet<>();
linkedSet.add("Apple");
linkedSet.add("Banana");
linkedSet.add("Cherry");
System.out.println("LinkedHashSet: " + linkedSet); // [Apple, Banana, Cherry]
// 3️⃣ TreeSet (중복X, 자동 정렬)
Set<String> treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Cherry");
treeSet.add("Apple");
System.out.println("TreeSet: " + treeSet); // [Apple, Banana, Cherry] (오름차순 정렬)
}
}
set은 중복을 허용하지 않기 때문에 set.add() 의 경우, 이미 값이 존재할 경우 false, 새로운 값 추가에 성공하면 true를 반환한다.
- set 메서드
메서드 설명 예제 add(E e) 요소 추가 (중복된 값이면 false 반환) set.add("Apple"); remove(Object o) 특정 요소 삭제 set.remove("Apple"); contains(Object o) 특정 요소가 존재하는지 확인 set.contains("Apple"); size() 저장된 요소 개수 반환 set.size(); isEmpty() Set이 비어있는지 확인 set.isEmpty(); clear() 모든 요소 삭제 set.clear(); iterator() Iterator 반환하여 요소 순회 Iterator<String> it = set.iterator(); toArray() Set을 배열로 변환 String[] arr = set.toArray(new String[0]);
import java.util.HashSet;
import java.util.Set;
public class SetExample {
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️⃣ 특정 값 확인
System.out.println("Apple 포함? " + set.contains("Apple")); // true
// 3️⃣ 요소 삭제
set.remove("Banana");
// 4️⃣ 크기 확인
System.out.println("Set 크기: " + set.size()); // 2
// 5️⃣ 모든 요소 출력 (for-each)
for (String fruit : set) {
System.out.println(fruit);
}
// 6️⃣ Set 비우기
set.clear();
System.out.println("Set이 비어있는가? " + set.isEmpty()); // true
}
}
2. Map (키-값 쌍을 저장하는 자료구조)
키(key)와 값(value)을 한 쌍으로 저장. 키(key) 값은 중복될 수 없다.
import java.util.*;
public class MapExample {
public static void main(String[] args) {
// 1️⃣ HashMap (순서 없음)
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 100);
hashMap.put("Banana", 200);
hashMap.put("Cherry", 150);
System.out.println("HashMap: " + hashMap);
// 2️⃣ LinkedHashMap (입력 순서 유지)
Map<String, Integer> linkedMap = new LinkedHashMap<>();
linkedMap.put("Apple", 100);
linkedMap.put("Banana", 200);
linkedMap.put("Cherry", 150);
System.out.println("LinkedHashMap: " + linkedMap);
// 3️⃣ TreeMap (자동 정렬)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Banana", 200);
treeMap.put("Cherry", 150);
treeMap.put("Apple", 100);
System.out.println("TreeMap: " + treeMap); // 키 기준 정렬
}
}
map.put() 은 새로운 키를 추가하면 null을 반환, 기존의 키의 키 값을 변경하면 기존의 값을 반환한다.
import java.util.HashMap;
import java.util.Map;
public class MapPutExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
// 새로운 값 추가 (반환값: null)
Integer result1 = map.put("Apple", 100);
System.out.println("첫 번째 추가: " + result1); // null
// 기존 키 값 변경 (반환값: 기존 값)
Integer result2 = map.put("Apple", 200);
System.out.println("두 번째 추가 (기존 값 반환): " + result2); // 100
// 새로운 키 추가 (반환값: null)
Integer result3 = map.put("Banana", 150);
System.out.println("세 번째 추가: " + result3); // null
}
}
- Map 메서드
| 메서드 | 설명 | 예제 |
| put(K key, V value) | 키-값 추가 (기존 값이 있으면 덮어쓰기) | map.put("Apple", 100); |
| get(K key) | 특정 키의 값 가져오기 | map.get("Apple"); |
| remove(K key) | 특정 키 삭제 | map.remove("Apple"); |
| containsKey(K key) | 특정 키가 존재하는지 확인 | map.containsKey("Apple"); |
| containsValue(V value) | 특정 값이 존재하는지 확인 | map.containsValue(100); |
| size() | 저장된 키-값 개수 반환 | map.size(); |
| isEmpty() | Map이 비어있는지 확인 | map.isEmpty(); |
| clear() | 모든 키-값 삭제 | map.clear(); |
| keySet() | 모든 키 반환 (Set<K> 형태) | Set<String> keys = map.keySet(); |
| values() | 모든 값 반환 (Collection<V> 형태) | Collection<Integer> values = map.values(); |
| entrySet() | 모든 키-값 쌍을 Set<Map.Entry<K, V>> 형태로 반환 | Set<Map.Entry<String, Integer>> entries = map.entrySet(); |
| putIfAbsent(K key, V value) | 키가 없을 때만 추가 | map.putIfAbsent("Apple", 100); |
| computeIfAbsent(K key, Function<K, V> mappingFunction) | 키가 없을 때 동적으로 값 추가 | map.computeIfAbsent("Apple", k -> 100); |
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
// 1️⃣ 요소 추가 (put)
map.put("Apple", 100);
map.put("Banana", 200);
map.put("Cherry", 150);
// 2️⃣ 특정 키의 값 가져오기
System.out.println("Apple의 값: " + map.get("Apple")); // 100
// 3️⃣ 특정 키 삭제
map.remove("Banana");
// 4️⃣ 키 존재 여부 확인
System.out.println("Banana 포함? " + map.containsKey("Banana")); // false
System.out.println("150 포함? " + map.containsValue("150")); // true
// 5️⃣ 모든 키-값 출력
// entrySet() -> 모든 키-값 쌍을 Set<Map.Entry<K, V>> 형태로 반환
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 6️⃣ 크기 확인
System.out.println("Map 크기: " + map.size()); // 2
}
}
3. ArrayList (가변 길이 리스트)
일반적으로 한번 선언된 string 타입의 배열인 string[] 는 string[] = new strint[size] 형식으로 선언하면 크기를 바꿀수 없음.
길이를 모르는 데이터를 저장할 때 사용함. 배열과 달리 크기가 동적으로 조정되며, 중복을 허용한다.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// 1️⃣ 리스트 선언
ArrayList<String> list = new ArrayList<>();
// 2️⃣ 요소 추가
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// 3️⃣ 특정 위치에 추가
list.add(1, "Grape"); // 1번 인덱스에 삽입
// 4️⃣ 요소 가져오기
System.out.println("첫 번째 요소: " + list.get(0));
// 5️⃣ 요소 삭제
list.remove("Banana");
// 6️⃣ 전체 출력
System.out.println("ArrayList: " + list);
}
}
list.get(index) 를 사용하여 특정 index의 값을 추출할 수 있다.
4. 2D Array
행과 열을 가진 배열로, 표 형태의 데이터를 저장할 때 사용
public class TwoDArrayExample {
public static void main(String[] args) {
// 1️⃣ 2D 배열 선언 및 초기화
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// 2️⃣ 특정 값 가져오기
System.out.println("matrix[0][0]: " + matrix[0][0]); // 1
// 3️⃣ 전체 출력 (이중 for문)
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
- 선언 방법
// (1) 크기만 지정 (기본값 0으로 초기화됨)
int[][] arr1 = new int[3][4]; // 3행 4열 배열
// (2) 선언 후 크기 할당
int[][] arr2;
arr2 = new int[2][3]; // 2행 3열 배열
// (3) 선언과 동시에 값 초기화
int[][] arr3 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// (4) 행 크기만 지정하고, 열 크기는 동적으로 할당
int[][] arr4 = new int[3][]; // 3행 선언, 열은 아직 미지정
arr4[0] = new int[2]; // 첫 번째 행은 2개의 열
arr4[1] = new int[3]; // 두 번째 행은 3개의 열
arr4[2] = new int[1]; // 세 번째 행은 1개의 열
'JAVA' 카테고리의 다른 글
| [Spring Boot] Websocket + STOMP를 이용한 세션 기반 채팅 (0) | 2025.09.23 |
|---|---|
| [SpingBoot] Api 호출시 Redis를 활용한 캐시 저장 (0) | 2025.04.04 |
| [프로그래머스] 가장 많이 받은 선물(2024 KAKAO WINTER INTERNSHIP) (0) | 2025.03.07 |
| [Spring Boot] 빈(Bean)이란? Autowired 란? (0) | 2025.03.07 |
| [Spring Boot] IntelliJ에서 Spring Boot와 MySQL 연동하기 (0) | 2025.02.19 |