Java_Map练习

package Hard.Map_;

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

public class MapExercise {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        HashMap hashmap = new HashMap();
        hashmap.put(1,new Employee("jack",1,2000));
        hashmap.put(2,new Employee("justin",2,2400));
        hashmap.put(3,new Employee("amy",3,2080));

        //使用keySet -> 增强for循环
        Set set = hashmap.keySet();
        for (Object key : set) {
            Employee emp = (Employee) hashmap.get(key);
            /*由于hashmap.get(key)方法的返回类型是Object,而期望的类型是Employee,
            所以需要将返回的对象强制转换为Employee类型。如果不进行强制转换,编译器会认为
            返回的是一个Object类型的对象,无法调用Employee对象的方法。
            * */
            if (emp.getSal()>2300){
                System.out.println(emp);
            }
        }

        //使用EntrySet -> 迭代器
        Set entryset = hashmap.entrySet();
        Iterator iterator = entryset.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            //通过entry取得key 和 value
            Employee emp = (Employee) entry.getValue();
            if (emp.getSal() > 2300){
                System.out.println(emp);
            }
        }

    }
}
class Employee{
    private String name;
    private int id;
    private double sal;

    public Employee(String name, int id, double sal) {
        this.name = name;
        this.id = id;
        this.sal = sal;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", sal=" + sal +
                '}';
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值