5、[简答题] 【HashMap存储键是自定义对象值是String】 一、请使用Map集合存储自定义数据类型Car做键,对应的价格做值。并使用keySet和entrySet两种方式遍历Map集合。

package day_04_test;

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

//5、[简答题]
//【HashMap存储键是自定义对象值是String】
//一、请使用Map集合存储自定义数据类型Car做键,对应的价格做值。并使用keySet和entrySet两种方式遍历Map集合。
public class Demo05 {
    public static void main(String[] args) {
        HashMap<Car, String> hashMap = new HashMap<>();
        hashMap.put(new Car("大众"), "100000");
        hashMap.put(new Car("本田"), "110000");
        hashMap.put(new Car("丰田"), "140000");
        //使用keySet
        Set<Car> carSet = hashMap.keySet();
        for (Car car:carSet
             ) {
            String value = hashMap.get(car);
            System.out.print("key:"+car.toString()+" ");
            System.out.print("value:"+value);
            System.out.println();
        }
        System.out.println("===============");
        //使用enteySet
        Set<Map.Entry<Car, String>> entrySet = hashMap.entrySet();
        for (Map.Entry<Car, String> entry:entrySet
             ) {
            System.out.print("key:"+entry.getKey());
            System.out.print("value:"+entry.getValue());
            System.out.println();
        }
    }
}
posted @ 2022-04-04 15:38  不只是智能hello  阅读(120)  评论(0)    收藏  举报