HashMap遍历之EntrySet

entry可以获取key和value的具体值

当entry 

 public static void main(String[] args) {
        Map map = new HashMap();
        map.put("邓超", "孙俪");//替换
        map.put("王宝强", "马蓉");//ok
        map.put(null, "刘亦菲");//pl
        map.put("鹿晗", null);//ok
        map.put("lu汉", "刘亦菲");
        map.put("沫年", "刘亦菲");//ok
        System.out.println(map);
        System.out.println("\n==========迭代器===========\n");
        Iterator ito3 = entrySet.iterator();
        while(ito3.hasNext()){
            Map.Entry entry2 = (Map.Entry) ito3.next();
            System.out.println(entry2.getValue());
        }

//        Iterator ito3 = entrySet.iterator();
//        while(ito3.hasNext()){
//          Object entry = ito3.next();
            System.out.println(entry);//HashMap$Node ---实现 > Map.Entry (getKey,getValue)
//          //向下转型 Map.Entry
//          Map.Entry m = (Map.Entry) entry;
//            System.out.print(m.getValue()+" ");
//        }
    }

当entry,此时value = Object  

    public static void main(String[] args) {
        /**
         * 使用HashMapp添加三个员工对象,要求
         * 键:员工id
         * 值:员工对象
         *
         * 并且遍历显示工资>18000的员工(遍历方式最少两种)
         * 员工类:姓名、工资、员工id
         */
        Map map = new HashMap();
        map.put(1, new Employee("smith", 18000, "20001206"));
        map.put(2, new Employee("tom", 28000, "20011212"));
        map.put(3, new Employee("smith", 10000, "20111010"));

        System.out.println("员工的个数为:" + map.size());
        System.out.println("=========第三种遍历方式=========");
       Set set = map.entrySet();//先将map转化为entrySet
       Iterator ito2 = set.iterator();//构建迭代器
       while (ito2.hasNext()){//迭代器循环条件
       Map.Entry entry = (Map.Entry) ito2.next();//将entrySet 转化为entry,并且向下移动指针
        //通过entry来获取key和value
       Employee emp = (Employee) entry.getValue();//将包entry向下转型为Employee
        System.out.println(emp);
    }
}

你可能感兴趣的:(韩顺平java习题,java,开发语言)