HashMap是一个实现Map接口的类。它基于哈希表。它允许空值和空键。
您可以将键值对存储在HashMap对象中。完成后,您可以检索各个键的值,但是,我们用于键的值应该是唯一的
put命令将值与指定的键关联。也就是说,如果我们在键已经存在的情况下添加键值对,则此方法将键的现有值替换为新值,
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 . . . . . ."); //检索哈希映射的值 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); //检索哈希映射的值 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(); } } }
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