hashMap hashSet hashtable遍历

public static void main(String[] args)
    {
        // hashMap
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("a", 0);
        map.put("b", 1);
        map.put("c", 2);
        System.out.println("hashMap遍历:");
        // 遍历1
        for (String str : map.keySet())
        {
            String key = str;
            int value = map.get(key);
            System.out.print("key:" + key + " value:" + value + " | ");
        }
        // 遍历2(效率高于1)
        System.out.println();
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.print("key:" + entry.getKey() + " value:" + entry.getValue() + " | ");
        }
        // 遍历3
        System.out.println();
        for (Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator(); iterator.hasNext();)
        {
            Map.Entry<String, Integer> entry = iterator.next();
            System.out.print("key:" + entry.getKey() + " value:" + entry.getValue() + " | ");
        }

        // hashSet
        Set<String> set = new HashSet<String>();
        set.add("a");
        set.add("b");
        set.add("c");
        System.out.println("\nhashSet遍历:");
        // 遍历1
        for (Iterator<String> iterator = set.iterator(); iterator.hasNext();)
        {
            System.out.print(iterator.next() + " | ");
        }
        // 遍历2
        System.out.println();
        for (String str : set)
        {
            System.out.print(str + " | ");
        }

        // Hashtable
        System.out.println("\nHashtable遍历:");
        Hashtable<String, Integer> hashtable = new Hashtable<String, Integer>();
        hashtable.put("d", 3);
        hashtable.put("e", 4);
        hashtable.put("f", 5);
        // 遍历1
        for (Iterator<String> iterator = hashtable.keySet().iterator(); iterator.hasNext();)
        {
            String key = (String) iterator.next();
            Integer value = hashtable.get(key);
            System.out.print("key:" + key + " value:" + value + " | ");
        }
        // 遍历key
        System.out.println();
        for (Enumeration<String> enumeration = hashtable.keys(); enumeration.hasMoreElements();)
        {
            System.out.print("key:" + enumeration.nextElement() + " | ");
        }
        // 遍历value
        System.out.println();
        for (Enumeration<Integer> enumeration = hashtable.elements(); enumeration.hasMoreElements();)
        {
            System.out.print("value:" + enumeration.nextElement() + " | ");
        }
    }


你可能感兴趣的:(HashMap,HashMap,HashMap,java编程思想,java编程思想)