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 hashMap = new HashMap<>();
        hashMap.put(new Car("大众"), "100000");
        hashMap.put(new Car("本田"), "110000");
        hashMap.put(new Car("丰田"), "140000");
        //使用keySet
        Set 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> entrySet = hashMap.entrySet();
        for (Map.Entry entry:entrySet
             ) {
            System.out.print("key:"+entry.getKey());
            System.out.print("value:"+entry.getValue());
            System.out.println();
        }
    }
}

相关