HashMap put() trong java dùng để thêm một cặp key – value vào HashMap. Nếu key đã chứa sẵn trong HashMap thì value sẽ được thay thế giá trị mới vừa được thêm vào.
Syntax
public V put(K key, V value);
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
// Mapping string values to int keys
hash_map.put(1, "share");
hash_map.put(4, "programming");
hash_map.put(5, "net");
System.out.println(hash_map);
hash_map.put(1, "haha");
System.out.println(hash_map);
}
}
Output:
{1=share, 4=programming, 5=net}
{1=haha, 4=programming, 5=net}