题目:使 用 HashMap 添 加 3 个 员 工 对 象 , 要 求 键 : 员 工 id 值 : 员 工 对 并 遍 历 显 示 工 资 > 18000 的 员 工 ( 遍 历 方 式 最 少 两 种 ) 员 工 类 : 姓 名 、 工 资 、 员 工 id
public static void main(String[] args) { Map map = new HashMap(); map.put(1,new Worker("tom",20000,10010)); map.put(2,new Worker("jason",19000,10011)); map.put(3,new Worker("mike",17000,10012)); //1.遍历 Set set = map.keySet(); for (Object key : set) { Worker worker = (Worker) map.get(key); if(worker.getSal() > 18000) System.out.println(key + ":" + map.get(key)); //1:tom 20000 10010 2:jason 19000 10011 } System.out.println("==================================="); //2.遍历 Set entrySet = map.entrySet(); for (Object entry : entrySet) { Map.Entry m = (Map.Entry) entry; Worker worker = (Worker) m.getValue(); if(worker.getSal() > 18000) System.out.println(m.getKey() + ":" + m.getValue()); //1:tom 20000 10010 2:jason 19000 10011 } } } class Worker{ private String name; private double sal; private int id; public Worker(String name, double sal, int id) { this.name = name; this.sal = sal; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return name + "\t" + sal + "\t" + id ; } }