자바-맵,집합,상수 집합
맵은 키(key)와 값(value)을 한 쌍으로 갖는 자료형
맵의 내장함수
import java.util.HashMap;
public class Sample {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("people", "사람");
map.put("baseball", "야구");
System.out.println(map.get("people")); // "사람" 출력
System.out.println(map.containsKey("people")); // true 출력
System.out.println(map.keySet()); // [baseball, people] 출력
System.out.println(map.remove("people")); // "사람" 출력
System.out.println(map.size());//1 출력
}
}
집합(Set) 자료형은 집합과 관련된 것을 쉽게 처리하기 위해 만든 것
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(Arrays.asList("H", "e", "l", "l", "o"));
System.out.println(set); // [e, H, l, o] 출력
}
}
집합 자료형은 중복을 허용하지 않기 때문에 자료형의 중복을 제거하기 위한 필터 역할로 종종 사용한다
교집합, 합집합,차집합
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> intersection = new HashSet<>(s1); // s1으로 intersection 생성
intersection.retainAll(s2); // 교집합 수행
System.out.println(intersection); // [4, 5, 6] 출력
HashSet<Integer> union = new HashSet<>(s1); // s1으로 union 생성
union.addAll(s2); // 합집합 수행
System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8, 9] 출력
HashSet<Integer> substract = new HashSet<>(s1); // s1으로 substract 생성
substract.removeAll(s2); // 차집합 수행
System.out.println(substract); // [1, 2, 3] 출력
}
}
집합 자료형과 관련된 메서드 - add, addAll, remove
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Jump");//add 함수
set.addAll(Arrays.asList("To", "Java"));//addAll 함수
System.out.println(set); // [Java, To, Jump] 출력
set.remove("To");
System.out.println(set); // [Java, Jump] 출력
}
}
enum 자료형은 서로 연관 있는 여러 개의 상수 집합을 정의할 때 사용
-간단한 java code
장점
- 매직 넘버를 사용할 때보다 코드가 명확하다.
- 잘못된 값을 사용해 생길 수 있는 오류를 막을 수 있다.