HashMap的两种取出方式keySet和entrySet

来源:互联网 发布:嵌入式单片机按钮模块 编辑:程序博客网 时间:2024/04/27 20:28
/*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 0
原创粉丝点击