java map 重复键_当我们尝试向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 map = new HashMap();

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  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  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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值