[Java] Chapter 2. HashMap

이지현·2023년 4월 10일
0

Java

목록 보기
38/46
post-thumbnail

✔️ HashMap

1. 특징

  • Array 장점 + List 장점 => 유연하면서도 빠르게 값을 찾아낼 수 있는 자료구조
  • key와 value 쌍으로 이루어짐

2. 종류별 시간복잡도

종류get()containsKey()next()
HashMapO(1)O(1)O(h/n)
LinkedHashMapO(1)O(1)O(1)
IdentityHashMapO(1)O(1)O(h/n)
WeakHashMapO(1)O(1)O(h/n)
EnumMapO(1)O(1)O(1)
TreeMapO(log n)O(log n)O(log n)
ConcurrentHashMapO(1)O(1)O(h/n)
ConcurrentSkipListMapO(log n)O(log n)O(1)
import java.util.HashMap;

// Map : Key -> Hash function -> Hash -> Bucket index -> Data
// HashMap : not synchronized
// HashTable : synchronized
// ConcurrentHashMap : synchronized + hash concurrency

public class practiceMap {
    public static void main(String[] args) {
        HashMap<String, Integer> map1 = new HashMap<>();

        // HashMap에 Key, Value 삽입
        map1.put("A", 1);
        map1.put("B", 2);
        map1.put("C", 3);
        System.out.println(map1); // {A=1, B=2, C=3}

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("D", 4);
        map2.put("E", 5);
        map2.put("F", 6);
        System.out.println(map2); // {D=4, E=5, F=6}

        // map 합치기
        map1.putAll(map2);
        System.out.println(map1); // {A=1, B=2, C=3, D=4, E=5, F=6}

        // 하나의 key/value 삭제
        map1.remove("C");
        System.out.println(map1); // {A=1, B=2, D=4, E=5, F=6}

        // map의 사이즈 반환
        System.out.println(map1.size()); // 5

        // map을 컬렉션 형태로 출력
        System.out.println(map1.values()); // [1, 2, 4, 5, 6]

        // map이 비어있는지 확인
        System.out.println(map1.isEmpty()); // false

        // key 값에 대한 value 값 출력
        System.out.println(map1.get("A")); // 1

        // 지정된 key 값 반환, 없으면 기본값 반환
        System.out.println(map1.getOrDefault("Z", 0)); // 0

        // map에 있는 값 모두 삭제
        map1.clear();
        System.out.println(map1); // {}

        Map<String, Integer> newMap = new HashMap<>();
        newMap.put("X", 1);
        newMap.put("Y", 2);
        newMap.put("Z", 3);

        // map에 저장된 모든 키 반환
        System.out.println(newMap.keySet()); // [X, Y, Z]

        // map의 모든 값 순회
        for(Map.Entry<String, Integer> entry : newMap.entrySet()) {
            System.out.print(entry.getKey() + ":" + entry.getValue() + " "); // X:1 Y:2 Z:3
        }
    }
}
profile
느슨하지 않게 꾸준히

0개의 댓글