java 自定义数据类型做键,使用keySet和entrySet两种方式遍历Map集合

2022-07-27,,,,

HashMap存储键是自定义对象值是String

请使用Map集合存储自定义数据类型Car做键,对应的价格做值。并使用keySet和entrySet两种方式遍历Map集合。

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        //使用Map集合存储自定义数据类型Car做键,对应的价格做值。
        Map<Car,Integer> map = new HashMap<>();
        map.put(new Car("客车","白色"),50000);
        map.put(new Car("轿车","黑色"),200000);
        map.put(new Car("火车","蓝色"),1000000);

        //使用keySet和entrySet两种方式遍历Map集合。
        System.out.println("使用keySet方式遍历Map集合:");
        Set<Car> key = map.keySet();
        for (Car keys : key) {
            int value = map.get(keys);
            System.out.println(keys + "  价格:" + value);
        }
        System.out.println("-----------------------------------------");

        System.out.println("使用entry方式遍历Map集合:");
        Set<Map.Entry<Car, Integer>> entries = map.entrySet();
        for (Map.Entry<Car, Integer> entry : entries) {
            System.out.println(entry.getKey() + "  价格:" + entry.getValue());
        }

    }


}

本文地址:https://blog.csdn.net/weixin_51311218/article/details/110286828

《java 自定义数据类型做键,使用keySet和entrySet两种方式遍历Map集合.doc》

下载本文的Word格式文档,以方便收藏与打印。