• map基本方法


    添加功能:

    V put(K key, V value)  添加和修改 ,添加时返回null,修改时返回被修改的值

        Map<String,String> map = new HashMap<String,String>();

      System.out.println(map.put("CS001","张三"));  //null

      System.out.println(map.put("CS001","李四"));  //张三

    判断功能:

    boolean containsKey(Object key)  判断指定的key是否存在

      System.out.println(map.containsKey("CS001"));  //true

    boolean containsValue(Object value)  判断指定的值是否存在

      System.out.println(map.containsValue("张三"));  //false

    boolean isEmpty()    判断是否是空map

      System.out.println(map.isEmpty());    //如果为空则返回true

    删除功能:

    void clear()  清空所有的对应关系 

      map.clear();

    V remove(Object key)    根据指定的key删除对应关系 ,并返回key对应的值,如果没有删除成功则返回null

      System.out.println(map.remove("CS003"));  //null

    获取功能:

    int size()  返回对应关系的个数

      System.out.println(map.size());

    V get(Object key)  根据指定的key返回对应的value

      System.out.println(map.get("CS001"));

    获取所有:

    Set<K> keySet()  以set形式返回所有的key    <K>看你创建map时key的类型

      Set<String> keys = map.keySet();   //因为key不允许重复,所以用set形式返回

      //遍历key 

      for (String key : keys){

        System.out.println(key);

      }

     Collection<V> values()  返回所有的value  <V>的类型跟创建map时value的类型一样

      Collection<String> values = map.values();    //map的value可以有重复值,所以不能用set形式返回

    遍历方法:

      1,先获取所有的key,通过遍历key 获取所有的值

        Set<String> keys = map.keySet();
        for (String key : keys){
            String value = map.get(key);
            System.out.println("KEY:" + key + "----" + "VALUE:" + value);
        }

      2,面相对向方式

      Set<Map.Entry<K,V>> entrySet() 

    class Entry<K,V>{
        K key;
        V value;
        
        public Entry(K key, V value){
            this.key = key;
            this.value = value;
        }
        
        public K getKey(){
            return key;
        }
        public V getValue(){
            return value;
        }
    }
    //以上为Entry对象 
    
    //创建map对象
    Map<String,String> map = new HashMap();
    //添加键值对
    map.add("a","A");
    map.add("b","B");
    map.add("c","C");
    //创建Entry对象
    Set<Map.Entry<String,String>> entrys = map.entrySet();
    //遍历entry对象
    for(Map.Entry<String,String> entry : entrys){
            //获取每个单独的entry对象
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println("KEY:" + key + "----" + "VALUE:" + value);
    }
  • 相关阅读:
    Go 环境变量相关操作
    Go命令行参数解析flag包
    go sync.once用法
    使用go语言编写IOS和Android程序
    go map的使用
    go runtime.Gosched()的作用分析
    go中的读写锁RWMutex
    go互斥锁Mutex
    go import使用及. _的作用解析
    利用channel在goroutins之间控制同步和传递数据
  • 原文地址:https://www.cnblogs.com/yifengs/p/10771202.html
Copyright © 2020-2023  润新知