zoukankan      html  css  js  c++  java
  • map hashmap的使用

    package map;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    /**
     * Map的实现类HashMap使用
     */
    public class MapTest {
        /**
         *
         */
        public static void main(String[] args) {
            System.out.println("MapGame start...");
            BasicUseOfHashMap();
            System.out.println("MapGame end...");
        }
    
        /**
         * HashMap的使用
         */
        private static void BasicUseOfHashMap() {
            Map<String, String> hashmap = new HashMap<>();
            hashmap.put("name", "eric");
            hashmap.put("sex", "男");
            String value = hashmap.get("sex");
            System.out.println(value);
            /**
             * 增强for循环遍历之使用entrySet循环遍历
             */
            System.out.println("
    " + "使用entrySet循环遍历");
            for (Map.Entry<String, String> entry : hashmap.entrySet()) {
                String key1 = entry.getKey();
                String value1 = entry.getValue();
                System.out.println(key1 + ":" + value1);
            }
            /**
             * 增强for循环遍历之使用keySet循环遍历
             */
            System.out.println("
    " + "使用keySet循环遍历");
            for (String key2 : hashmap.keySet()) {
                System.out.println(key2 + ":" + hashmap.get(key2));
            }
            /**
             * 迭代器循环遍历之使用keySet()遍历
             */
            System.out.println("
    " + "迭代器循环遍历之使用keySet()遍历");
            Iterator<String> iterator = hashmap.keySet().iterator();
            while (iterator.hasNext()) {
                String key3 = iterator.next();
                System.out.println(key3 + ":" + hashmap.get(key3));
            }
            /**
             * 迭代器循环遍历之使用entrySet()遍历
             */
            System.out.println("
    " + "迭代器循环遍历之使用keySet()遍历");
            Iterator<Map.Entry<String, String>> iterator1 = hashmap.entrySet().iterator();
            while (iterator1.hasNext()) {
                Map.Entry<String, String> map = iterator1.next();
                String key4 = map.getKey();
                String value4 = map.getValue();
                System.out.println(key4 + ":" + value4);
            }
        }
    
    
    }
    

       java中为什么要使用Iterator?

          Iterator模式是用于遍历集合类的标准访问方法。它可以把访问逻辑从不同类型的集合类中抽象出来,从而避免向客户端暴露集合的内部结构。

    参考资料:https://www.cnblogs.com/lzq198754/p/5780165.html#top

  • 相关阅读:
    ThreadLocal的原理和使用场景
    sleep wait yield join方法的区别
    GC如何判断对象可以被回收
    双亲委派
    ConcurrentHashMap原理,jdk7和jdk8版本
    hashCode和equals
    接口和抽象类区别
    为什么局部内部类和匿名内部类只能访问局部final变量
    【GAN】基础GAN代码解析
    TF相关codna常用命令整理
  • 原文地址:https://www.cnblogs.com/jycjy/p/10802827.html
Copyright © 2011-2022 走看看