콜렉션 프레임워크 - HashMap

2019-09-07

HashMap


import java.util.HashMap; 
import java.util.Map; 
  
public class Test 
{ 
    public static void main(String[] args)  
    { 
      
        HashMap<String, Integer> map = new HashMap<>(); 
          
        print(map); 
        map.put("vishal", 10); 
        map.put("sachin", 30); 
        map.put("vaibhav", 20); 
          
        System.out.println("Size of map is:- " + map.size()); 
      
        print(map); 
        if (map.containsKey("vishal"))  
        { 
            Integer a = map.get("vishal"); 
            System.out.println("value for key \"vishal\" is:- " + a); 
        } 
          
        map.clear(); 
        print(map); 
    } 
      
    public static void print(Map<String, Integer> map)  
    { 
        if (map.isEmpty())  
        { 
            System.out.println("map is empty"); 
        } 
          
        else
        { 
            System.out.println(map); 
        } 
    } 
} 

Output:

map is empty
Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key "vishal" is:- 10
map is empty

HashMap은 Java에서 Map 인터페이스를 구현하기 위해 사용된다.

HashMap은 데이터를 (key, value) 쌍으로 저장한다.

값에 접근하기 위해서는 반드시 key값을 알아야 한다.

Hashing이란 긴 길이의 string을 같은 string을 나타내는 작은 string으로 변환하는 기술이다.

이 변환된 짧은 값은 색인화 및 검색 속도를 빠르게 한다.

HashMap은 노드 배열을 포함하며 이 노드는 4개의 필드를 포함하는 클래스로 표현된다.

  1. int hash
  2. K key
  3. V value
  4. Node next

Key 값은 중복이 불가능하고 value는 중복이 가능하며 null도 사용 가능하다.


HashMap의 대표적인 메소드를 소개하겠다.

map.clear();

저장된 모든 객체를 제거한다.

map2 = (Hashmap)map.clone;

HashMap을 복제하고 반환한다.

boolean containsKey(Object Key)

boolean containsValue(Object Value)

contain하고 있으면 true, 아니면 false

Set set = map.entrySet();

key-value 값을 결합한 형태로 set에 저장하여 반환한다.

import java.util.*; 
  
public class Hash_Map_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty HashMap 
        HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 
  
        // Mapping int values to string keys 
        hash_map.put("Geeks", 10); 
        hash_map.put("4", 15); 
        hash_map.put("Geeks", 20); 
        hash_map.put("Welcomes", 25); 
        hash_map.put("You", 30); 
  
        // Displaying the HashMap 
        System.out.println("Initial Mappings are: " + hash_map); 
  
        // Using entrySet() to get the set view 
        System.out.println("The set is: " + hash_map.entrySet()); 
    } 
} 

Output:

Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The set is: [4=15, Geeks=20, You=30, Welcomes=25]

Object get(Object Key)

key로 값을 찾아 반환한다.

map.put("hello", "world");

val = (String)map.get("hello")

Set keySet()

모든 키가 저장된 set을 반환한다.


HashTable은 HashMap과 마찬가지로 Map 인터페이스를 상속받아 구현한다.

가장 큰 차이점으로 HashTable은 동기화(Synchronization)되어있다는 차이가 있다.

하지만 Vector가 ArrayList와 달리 다중 스레드 환경을 지원함에도 성능에 밀려 그다지 권장되지 않는 것처럼,

HashTable보다는 HashMap을, 동기화가 필요하다면 ConcurrentHashMap을 쓰는 것이 더 낳은 선택일 수도 있다.