当我们尝试在 Java 中向 HashMap 对象中添加重复键时会发生什么?
HashMap 是一个实现 Map 接口的类。它基于哈希表。它允许 null 值和 null 键。
您可以在 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 . . . . . .");
//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();
}
}
}输出
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP