life--

Java【使用HashMap类实例化一个Map类型的对象】

题目:

  1. 使用HashMap类实例化一个Map类型的对象m1,键(String类型)和值(int型)分别用于存储员工的姓名和工资,存入数据如下: 张三——800元;李四——1500元;王五——3000元;
  2. 将张三的工资更改为2600元
  3. 为所有员工工资加薪100元;
  4. 遍历集合中所有的员工
  5. 遍历集合中所有的工资

大体思路:

1.实例化HashMap,存入String类型的key,int类型的Value

2.使用hashMap的replace方法修改工资

3.使用hashMap的keySet方法,将所有键存入Set集合中,通过增强for循环使用hashMap的replace方法,输入key和Value的数值+100实现每个员工加薪100

4.使用迭代器遍历

代码:

复制代码
public class salary{
    public static void main(String[] args) {
        Map<String,Integer> hashmap=new HashMap();
        hashmap.put("张三",800);
        hashmap.put("李四",1500);
        hashmap.put("王五",3000);
        //此处使用put和replace结果相同
        hashmap.replace("张三",2600);

        //使用hashmap的keySet方法将key的数值传递给strings
        //在增强for循环过程中使用hashmap的replace方法将string位置的value换成原本数据+100
        //replace换put方法也可以
        Set<String> strings = hashmap.keySet();
        for (String string : strings) {
            hashmap.replace(string,hashmap.get(string)+100);
        }

        //遍历所有员工(懒得分开,放一起写了)
        Iterator<Map.Entry<String, Integer>> iterator = hashmap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Integer> next = iterator.next();
            System.out.println(next.getKey());
            System.out.println(next.getValue());
        }
    }
}
复制代码

 

posted on   life--  阅读(484)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示