当我们尝试向Java中的HashMap对象添加重复键时会发生什么?
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
热门推荐
10 新婚祝福语简短句子
11 贺卡文字同事祝福语简短
12 满岁女宝祝福语简短
13 贺卡祝福语宝宝男孩简短
14 自由旅行祝福语简短英文
15 送菜的祝福语简短霸气
16 升职祝福语朋友简短精辟
17 祝福语勤奋大全简短英语
18 过年祝福语南昌话简短