hashMap的三种遍历方式


    public void testClass(){
        HashMap hashMap = new HashMap();
        hashMap.put("1", "1");
        hashMap.put("2", "2");
        Set> entrySet = hashMap.entrySet();
        Iterator> iterator = entrySet.iterator();
        //1.迭代器实现 效率高
        while(iterator.hasNext()){
            Entry entry = iterator.next();
            String key = entry.getKey();
            System.out.println(key);
            String value = entry.getValue();
            System.out.println(value);
        }
        //2.entrySet
        for (Entry entry : entrySet) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        //3.keySet
        Set keySet = hashMap.keySet();
        for (String entry : keySet) {
            System.out.println(hashMap.get(entry));
        }
    }

你可能感兴趣的:(JavaSE)