[자료구조] HashMap개요 및 사용법

지니·2025년 2월 27일

자료구조

목록 보기
3/9
post-thumbnail

1.HashMap이란?


1-1. Map이란?

Map은 Key(중복 불가)와 Value(중복 가능)을 쌍으로 저장하는 자료구조이다.

1-2. HashMap의 특징

  • Map인터페이스를 구현하는 클래스 중에서 가장 자주 사용되는 클래스이다.
  • 저장은 느리지만, 검색 측면에서는 뛰어나다.
  • 중복된 키 값에 값을 저장하면 기존의 값에 새로운 값이 덮어 씌어진다.

2. HashMap 사용법


2-1. HashMap의 메서드


2-2. HashMap 선언 및 사용

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        /* 1. 문자열 타입을 키, 값으로 하는 HashMap */
        HashMap<String, String> hmap = new HashMap<>();

        // 2. put 메소드를 이용해 entry 넣기
        hmap.put("one", "java");
        hmap.put("two", "mysql");

        // 3. get과 getOrDefault 이용해 값 가져오기.
        System.out.println(hmap.get("one")); // java 출력
        System.out.println(hmap.getOrDefault("two","no")); // mysql 출력
        System.out.println(hmap.getOrDefault("three","no")); // no 출력

        // 4. containsKey와 containsValue를 이용해 값의 존재 유무 파악
        System.out.println(hmap.containsKey("one")); // true
        System.out.println(hmap.containsKey("three")); // false
        System.out.println(hmap.containsValue("java")); // true
        System.out.println(hmap.containsValue("jdbc")); // false

        // 5. replace를 이용해 값 바꾸기
        hmap.replace("one","jdbc"); // value값이 jdbc로 변경
        hmap.replace("two","mysql","html"); // value값이 html로 변경
        hmap.replace("two","css","html"); // value값이 변경되지 않음


        // 6. entrySet으로 set값으로 값을 가져오기
        System.out.println(hmap.entrySet()); // 가져올 때, {}에서 []로 출력

        // 7. isEmpty()로 값이 비어있는지 확인
        System.out.println(hmap.isEmpty()); // false 출력

        // 8. remove와 clear로 값 삭제하기
        System.out.println(hmap.remove("one")); // 해당하는 entry가 삭제됨
        hmap.clear(); // 모든 entry가 삭제됨
        System.out.println(hmap.isEmpty()); // true

    }
}

3. HashSet이나 Hashmap을 사용하는 문제


3-1. 프로그래머스

3-2. 백준


참고 : https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

0개의 댓글