• Home

My Codegate

  • Home

자바 Map.get 사용 시 NullPointerException 에러 해결방법

2023/12/11 Posted by Codegate Java No Comments
자바 Map.get 사용 시 NullPointerException 에러 해결방법

자바에서 Map.get(key); 메소드 사용 시 key에 해당하는 값이 없으면 Null을 넣어줄 수 없는 변수의 경우에는 Exception in thread “main” java.lang.NullPointerException: Cannot invoke “java.lang.Integer.intValue()” because the return value of “java.util.HashMap.get(Object)” is null 이런 에러가 발생하게 되는데

public class Sample {

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

    if(map.get("test") == null) {
      // code
    } else {
      // code
    }
  }
}


값이 null일 경우를 대비한 if 문을 만들어서 처리할 수도 있겠지만, map에서 null일 경우를 대비한 getOrDefault(key, defaultValue);를 지원하는데

null일 경우에는 지정된 값이 들어오게 할 수 있으니 NullPointerException이 발생할 수 있는 경우라면 .get() 대신 .getOrDefault()를 사용해주면 되겠다.

No Comments
2

Leave a Reply Cancel Reply

Introduction

My Codegate

Latest Posts

  • Google Search Console API 연동방법
  • 인텔리제이 Gradle Dependency 최신 버전 보는 방법
  • Wallet-Tracker 개발일지
  • Moralis API 자바로 호출방법
  • IntelliJ Commit 후 Push 따로 하는 방법

Categories

  • My Project (4)
  • Java (42)
  • Algorithm (161)
    • Java (152)
    • Algorithm Knowledge (3)
    • Algorithm site usage (6)
  • Vue.js (1)
  • Spring (4)
  • Docker (2)
  • IntelliJ (20)
  • Uncategorized (7)

Recent Comments

  • Codegate on Hello world!
  • A WordPress Commenter on Hello world!

© 2025 — mycodegate.com

Prev Next