new HashMap
new HashMap<[type, type]>()
HashMap<> map = new HashMap<>(); //type없음, Object 입력
HashMap<Integer, Integer> map1 = new HashMap<>(); //type 설정
HashMap<Integer, Integer> map2 = new HashMap<>(map2); //map2 카피
HashMap<Integer, Integer> map3 = new HashMap<>(10); //초기용량 설정
- put
- putIfAbsent
put(K key, V value)
putIfAbsent(K key, V value)
map.put(0, "vlaue1"); //mep.get(0) => value1
map.put(0, "value2"); //mep.get(0) => value2
map.putIfAbsent(0, "value3"); //mep.get(0) => value2
- remove
- clear
remove(K key)
map.remove(1);
clear()
map.clear();
- get
- KeySet
- values
- entrySet
- Iterator
get(Object key)
String value = map.get(1);
KeySet()
- 반환형: Set<k>
values()
- 반환형: Collection<v>
System.out.println("map.keySet() = " + map.keySet());
System.out.println("map.values() =" + map.values());
출력
map.keySet() = [1, 2, 3]
map.values() =[a, b, c]
enterySet()
for (Entry<Integer, String> entry : map.entrySet()) {
System.out.print("key: " + entry.getKey());
System.out.println(", value: " + entry.getValue());
}
출력
key: 1, value: a
key: 2, value: b
key: 3, value: c
Iterator
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
System.out.println("key: "+ entry.getKey()+
", value: "+entry.getValue());
}
출력
key: 1, value: a
key: 2, value: b
key: 3, value: c
- replace
- size
- contains
- getOrDefault
- putIfAbsent
replace(K key, V new_value)
size()
- 반환형: int
containsKey(Object key)
conatinValue(Object value)
System.out.println(map.containsKey(1)); //true
System.out.println(map.containsValue("d")); //false
map.getOrDefault(Object key, V defaultValue)
System.out.println("get 메서드: " + map.get(4));
System.out.println("getOrDefault 메서드: " + map.getOrDefault(4, "d"));
출력
get 메서드: null
getOrDefault 메서드: d