본문 바로가기
안드로이드/JAVA

[JAVA] 안드로이드 HashMap 사용하기

by 프로나인 2020. 8. 20.

반갑습니다! 프로나인 입니다.

 

저저번 주만 해도 장마철이여 빨리 끝나라!!! 이랬는데

장마철이 끝나자마자 엄청난 폭염이 찾아와서 진짜 너무너무너무 더운데 다들 더위 조심하세요 ㅠ

 

오늘은 HashMap을 사용하는 방법을 알아보도록 하겠습니다.

 


HashMap 이란?

HashMap은 Map 인터페이스를 구현한 대표적인 Map 컬렉션입니다.

또 Key와 Value의 쌍으로 이루어진 데이터를 보관을 합니다.

 

HashMap의 특징

 

  • 데이터가 삽입되는 순서와 저장되는 순서가 같다는 보장이 되지 않는다.
  • key와 value 가 null을 허용한다.
  • key는 중복을 허용하지 않는다.

 

HashMap 사용법 

HashMap에는 위에 사진처럼 여러 가지 API을 제공합니다. 예제를 통해 알아보도록 하겠습니다.

put()

Map<String, String> animal = new HashMap<>();
animal.put("cat", "one");
animal.put("dog", "two");
animal.put("pig", "three");
animal.put(null,"four");
System.out.println("animal : " + animal);

put() 결과

이때 HashMap의 특징으로 null도 허용하기 때문에 null도 put이 가능합니다.

putAll()

putAll은 두 개의 Map을 합칠 때 사용합니다.

Map<String, Integer> animal = new HashMap<>();
animal.put("cat", 1);
animal.put("dog", 3);
animal.put("pig", 5);
animal.put(null, 2);

Map<String, Integer> food = new HashMap<>();
food.put("coffee", 3);
food.put("chicken", 1);
food.put("pizza", 2);

animal.putAll(food);
System.out.println("food : " + food);
System.out.println("animal : " + animal);

putall() 결과

여기서 한 가지 알고 가셔야 할 것은 Map선언 시 같은 타입일 때만 putAll이 가능합니다.

예시로 Map<String, Integer> 와 Map<String, String> 은 putAll이 불가능합니다!

get()

get()은 key에 해당하는 value의 값을 리턴해줍니다. 이때 key가 존재하지 않으면 null을 리턴합니다.

Map<String, Integer> animal = new HashMap<>();
animal.put("dog",1);
animal.put("pig",2);
animal.put("cat",5);

System.out.println("dog : " + animal.get("dog"));
System.out.println("pig : " + animal.get("pig"));
System.out.println("cat : " + animal.get("cat"));
System.out.println("fish : " + animal.get("fish"));

get() 결과

remove()

remove()는 key에 해당하는 데이터를 삭제합니다. 삭제가 되면 value값이 리턴됩니다.

Map<String, Integer> fruits = new HashMap<>();
fruits.put("apple", 2);
fruits.put("banana", 5);
fruits.put("pear", 7);

System.out.println("apple : " + fruits.get("apple"));
System.out.println("apple : " + fruits.remove("apple"));
System.out.println("melon : " + fruits.remove("melon"));
System.out.println("apple : " +fruits.get("apple"));

remove() 결과

순서대로 보면 remove를 하였을 때 remove 한 value 값을 리턴해서 보여주고 있습니다. 

그리고 다시 apple을 get 하면 데이터가 지워진 것을 확인할 수 있습니다.

 

keySet()

keySet()은 HashMap에 저장된 Key들을 리턴해줍니다.

Map<String , Integer> animal = new HashMap<>();
animal.put("dog", 2);
animal.put("pig", 5);
animal.put("cat", 3);

System.out.println("animal_keyset : " + animal.keySet());

keySet() 결과

 


HashMap을 사용하면서 가장 많이 쓰이는 API들을 정리해 보았습니다.

이외에도 HashMap API는 다양하고 또 어떻게 사용하는지에 따라 유용하게 사용할 수 있습니다.

 

HashMap을 Android로 예시 역시 들어 놓았지만 뭔가 직관적으로 표현을 할 수 있는 게 더 좋아서 System.out을 사용하여 보여드렸습니다.

Android예시로 들은 것은 아래 Github에 올려둘 테니 참고하시기 바랍니다!

 

코드 & 참조

github.com/Koo-hee/Android-hashmap

 

Koo-hee/Android-hashmap

java-hashmap. Contribute to Koo-hee/Android-hashmap development by creating an account on GitHub.

github.com

댓글