HashMap implement interface Map, dựa trên Hash table. Cho phép null key và null value.
Lưu cặp key-value trong HashMap. Key phải unique.
Giá trị trùng lặp
put() liên kết value với key. Nếu thêm cặp key-value mà key đã tồn tại, phương thức thay thế value cũ bằng value mới.
Ví dụ
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class DuplicatesInHashMap { public static void main(String args[]) { HashMap<String, Long> map = new HashMap<String, Long>(); map.put("Krishna", 9000123456L); map.put("Rama", 9000234567L); map.put("Sita", 9000345678L); map.put("Bhima", 9000456789L); map.put("Yousuf ", 9000456789L); System.out.println("Values Stored . . . . . ."); //Retrieving the values of a Hash map Iterator it1 = map.entrySet().iterator(); System.out.println("Contents of the hashMap are: "); while(it1.hasNext()){ Map.Entry <String, Long> ele = (Map.Entry) it1.next(); System.out.print(ele.getKey()+" : "); System.out.print(ele.getValue()); System.out.println(); } map.put("Bhima", 0000000000L); map.put("Rama", 0000000000L); //Retrieving the values of a Hash map Iterator it2 = map.entrySet().iterator(); System.out.println("Contents of the hashMap after inserting new key-value pair: "); while(it2.hasNext()){ Map.Entry <String, Long> ele = (Map.Entry) it2.next(); System.out.print(ele.getKey()+" : "); System.out.print(ele.getValue()); System.out.println(); } } }
Kết quả
Values Stored . . . . . . Contents of the hashMap are: Yousuf : 9000456789 Krishna : 9000123456 Sita : 9000345678 Rama : 9000234567 Bhima : 9000456789 Contents of the hashMap after inserting new key-value pair: Yousuf : 9000456789 Krishna : 9000123456 Sita : 9000345678 Rama : 0 Bhima : 0