HashMap的两种取出方式keySet和entrySet

/*HashMap的两种取出方式keySet和entrySet
每一个学生都有对应的归属地。
学生Student,地址String.
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。

1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3.获取map集合中的元素。
*/
class Student implements Comparable<Student>//实现比较性< ? super E>
{
    private String name;
    private int age;
    Student(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    public int compareTo(Student s)//重写compareTo()方法
    {
        int num = new integer(this.age).compareTo(new Integer(s.age));//先比较age
        if(num==0)
            return this.name.compareTo(s.name);//再比较name
        return num;
    }
    public int hashCode()//重写hashCode()
    {
        return name.hashCode()+age*34;
    }
    public boolean equals(Object obj)//重写equals()
    {
        if (! (obj instanceof Student))
            throw new ClassCastException("类型不匹配");//类型转换异常
        Student s = (Student)obj;//强制转换类型
        return this.name.equals(s.name) && this.age==s.age;//判断后存入Hash表
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public String toString()
    {
        return name+":"+age;
    }
}
class MapTest 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello World!");

        HashMap<Studengt,String> hm = new HashMap<Studengt,String>();

        hm.put(hm.put(new Student("lisi1",21),"beijing"));//put(K key, V value)存入
        hm.put(hm.put(new Student("lisi1",21),"tianjin"));
        hm.put(hm.put(new Student("lisi2",22),"shanghai"));
        hm.put(hm.put(new Student("lisi3",23),"nanjing"));
        hm.put(hm.put(new Student("lisi4",24),"wuhan"));

        //第一种取出方式 keySet

        Set<Student> keySet = hm.keySet();
        Iterator<Student> it = keySet.iterator();

        while(it.hasNext())
        {
            Student stu = it.next();
            String addr = hm.get(stu);//传入值key,返回值是<k,v>里面的value
            System.out.println(stu+"..."+addr);
        }

        //第二种取出方式entrySet
        //Map.Entry是一种接口再实现内部接口
        Set<Map.Entry<Student,String> entrySet = hm.next();
        Iterator<Map.Entry<Student,String> iter = entrySet.iterator();
        while(it.hasNext())
        {
            Map.Entry<Student,String> me = iter.next();
            Student stu = me.getKey();
            String addr = me.getValue();
            System.out.println(stu+"..."+addr);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值