728x90
면접 때 자주 사용하게 되는
HashMap의 method들 정리 노트
1. put(K key, V value)
hashmap에 추가 하는 방법
V put (K key, value);
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
// Key = String, Value = Integer
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // Output: {a=1,b=2,c=3}
map.put("a", 100); // updates value of an existing key "a"
System.out.println(map); // Output: {a=100,b=2,c=3}
}
}
2. get(Object key)
get에 key를 넣으면
value를 돌려준다.
V get (Object key)
System.out.println(map.get("a")); // output: 100
System.out.println(map.get("b")); // output: 2
System.out.println(map.get("z")); // output: null
3. containsKey(Object key)
containsKey에 확인하고 싶은 key를 넣으면
hashmap에 있는지 없는지 알려줌
boolean containsKey(Object key)
System.out.println(map.containsKey("a")); // output: true
System.out.println(map.containsKey("c")); // output: true
System.out.println(map.containsKey("z")); // output: false
4. containsValue(Object value)
위의 containsKey와 비슷한데,
그냥 value가 있는지 확인하는 방법
boolean containsValue(Object value)
System.out.println(map.containsValue(100)); // output: true;
System.out.println(map.containsValue(1)); // output: false;
5. remove(Object key)
key-value 페어에서 key를 없애줌.
만약 그 키가 있었다면 키의 값을 리턴하고
없었다면 null
V remove(Object key)
System.out.println(map.remove("a")); // output: 100
System.out.println(map); // output: {b=2, c=3}
System.out.println(map.remove("b")); // output: 2
System.out.println(map); // output: {c=3}
System.out.println(map.remove("z")); // output: null
6. size()
key-value 페어 갯수 알려주는 사이즈
int size()
System.out.println(map.size()); //output: 1
7. isEmpty()
boolean isEmpty()
hashmap에 key-value 페어가 있는지 없는지 알려줌
System.out.println(map.isEmpty()); //output: false
개인적인 공부용 노트이므로
다들 그냥 적당히 참고만 하세유
728x90