HashMap là lớp con của AbstractMap dùng để lưu trữ cặp khóa & giá trị. Mỗi khóa ánh xạ tới một giá trị duy nhất và khóa là duy nhất. Chúng ta thêm phần tử bằng phương thức put() và duyệt bằng interface Iterator.
Cú pháp
public V put(K key, V value)
Ví dụ
import java.util.*;
import java.util.Map.*;
public class HashMapTest {
public static void main(String[] args) {
HashMap map = new HashMap();
// thêm phần tử vào hashmap bằng put()
map.put("1", "Adithya");
map.put("2", "Jai");
map.put("3", "Chaitanya");
map.put("4", "Krishna");
map.put("5", "Ramesh");
if(!map.isEmpty()) {
Iterator it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry obj = (Entry)it.next();
System.out.println(obj.getValue());
}
}
}
}
Kết quả
Adithya Jai Chaitanya Krishna Ramesh