Java 核心技术(第八版)卷1:基础知识:例13-5P582MapTest

import java.util.*;
//本程序演示 map 的使用,它的key 是 String,值是Employee类型
public class MapTset {
    public static void main(String[]args)
    {
        Map<String,Employee> staff=new HashMap<String,Employee>();
        staff.put("144-25-5464",new Employee("Amy Lee"));
        staff.put("567-24-2546",new Employee("Harry Hacker"));
        staff.put("157-62-7935",new Employee("Gary Cooper"));
        staff.put("456-62-5527",new Employee("Francersca Cruz"));

        // print all entries
        System.out.println(staff);
        //remove an entry
        staff.remove("567-24-2546");
        System.out.println("After remove Key:567-24-2546 :");
        System.out.println(staff);
        //replace an entry
        staff.put("456-62-5527",new Employee("Francesca Miller"));
        System.out.println("After replace Key:456-62-5527 :");
        System.out.println(staff);
        //iterate through all entries
        System.out.println("Let have a iteration:");
        for(Map.Entry<String,Employee> entry:staff.entrySet())
        {
            String key=entry.getKey();
            Employee value=entry.getValue();
            System.out.println("key="+key+",value="+value);
        }




    }
}
//mini employee class for test purpose
class Employee
{
    public Employee(String n)
    {
        name=n;
        salary=0;
    }
    public String toString()
    {
        return "[name="+name+",salary="+salary+"]";
    }

    private String name;
    private double salary;
}

运行结果:

{157-62-7935=[name=Gary Cooper,salary=0.0], 144-25-5464=[name=Amy Lee,salary=0.0], 456-62-5527=[name=Francersca Cruz,salary=0.0], 567-24-2546=[name=Harry Hacker,salary=0.0]}
After remove Key:567-24-2546 :
{157-62-7935=[name=Gary Cooper,salary=0.0], 144-25-5464=[name=Amy Lee,salary=0.0], 456-62-5527=[name=Francersca Cruz,salary=0.0]}
After replace Key:456-62-5527 :
{157-62-7935=[name=Gary Cooper,salary=0.0], 144-25-5464=[name=Amy Lee,salary=0.0], 456-62-5527=[name=Francesca Miller,salary=0.0]}
Let have a iteration:
key=157-62-7935,value=[name=Gary Cooper,salary=0.0]
key=144-25-5464,value=[name=Amy Lee,salary=0.0]
key=456-62-5527,value=[name=Francesca Miller,salary=0.0]

进程已结束,退出代码0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值