티스토리 뷰

JAVA

Collection framework - HashMap

seoca 2019. 7. 23. 07:18

 

 

HashMap<key,value>

 

  • HashMap is not thread-safe which allows you faster speed than HashTable.
  • HashMap doesn't allow insertion order. *Use LinkedHashMap to preserve the fixed order.
  • key doesn't allow duplicate key, but for value, duplication is allowed.

 

 

 

put() - key, value map에 입력

get() - key를 전달해야 그 key의 value가 반환된다. 

remove() - 해당 key의 key와 value 삭제

 

 

 

Example Code

import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        String[] fruit = {"apple""banana""cherry"};
        Map<Integer,String> hash = new HashMap<>();
 
        for (int i = 0; i < fruit.length; i++) {
            hash.put(i,fruit[i]); //auto-boxing
        }
        
        hash.put(0,"kiwi");
        
        System.out.println(hash.get(0)); //kiwi
        System.out.println(hash.get(1)); //banana
        System.out.println(hash.get(2)); //cherry
 
        hash.remove(0);
 
        System.out.println(hash.get(0)); //null
 
    }
}

'JAVA' 카테고리의 다른 글

Java is Pass-By-Value  (0) 2019.07.27
Arrays.sort in Java  (0) 2019.07.23
keySet() in Java  (0) 2019.07.23
Map - getOrDefault(), putIfAbsent() in Java  (0) 2019.07.23
Java IOException - Stream Closed  (0) 2019.07.19