又一道HashMap简单例子

本文通过一个Java示例展示了如何使用HashMap来存储和检索电话号码。包括添加条目、遍历键值对、复制映射以及移除条目的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java 代码
  1. public class HashMapDemo{   
  2.   
  3.         public static void main(String [] args){   
  4.   
  5.                 HashMap emPhone = new HashMap();   
  6.   
  7.                 emPhone.put("Ashish","111-222-3333");   
  8.                 emPhone.put("Archit","444-555-6666");   
  9.                 emPhone.put("Prashant","777-888-9999");   
  10.   
  11.                 Set keys = emPhone.keySet();//Set类可以获取HashMap对象的键。   
  12.                 Iterator keyIter = keys.iterator();   
  13.                 while(keyIter.hasNext()){   
  14.                         String nextName = (String)keyIter.next();   
  15.                         String phoneNum = (String)emPhone.get(nextName);   
  16.                         System.out.println(nextName + ":" + phoneNum);   
  17.                 }   
  18.   
  19.                 String phoneName = (String)emPhone.remove("Ashish");   
  20.                 System.out.println("Removed Ashish's number :" + phoneName);   
  21.   
  22.                 HashMap newEmpPhone = new HashMap();   
  23.   
  24.                 newEmpPhone.putAll(emPhone);   
  25.                 int dirSize = newEmpPhone.size();   
  26.                 System.out.println("Created new phone directory with " + dirSize + " numbers...");   
  27.   
  28.                 phoneName = (String)newEmpPhone.get("Prashant");   
  29.                 System.out.println("Prashant's number in new director: " + phoneName);   
  30.   
  31.         }   
  32.   
  33. }    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值