记录JAVA集合学习-map

2019-07-13  本文已影响0人  ccccaixiaohao

1.Map接口和Collection接口的不同

Map是双列的,Collection是单列的
Map的键唯一,Collection的子体系Set是唯一的
Map集合的数据结构值针对键有效,跟值无关;Collection集合的数据结构是针对元素有效

2.Map集合的功能概述

* a:添加功能
    * V put(K key,V value):添加元素。
        * 如果键是第一次存储,就直接存储元素,返回null
        * 如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
* b:删除功能
    * void clear():移除所有的键值对元素
    * V remove(Object key):根据键删除键值对元素,并把值返回
* c:判断功能
    * boolean containsKey(Object key):判断集合是否包含指定的键
    * boolean containsValue(Object value):判断集合是否包含指定的值
    * boolean isEmpty():判断集合是否为空
* d:获取功能
    * Set<Map.Entry<K,V>> entrySet():
    * V get(Object key):根据键获取值
    * Set<K> keySet():获取集合中所有键的集合
    * Collection<V> values():获取集合中所有值的集合
* e:长度功能
    * int size():返回集合中的键值对的个数

entrySet():将键值对封装成一个对象进行返回

public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("test1", 12);
        map.put("test2", 23);
        map.put("test3", 43);
        map.put("test4", 35);
        map.put("test5", 33);
        
        Set<Entry<String, Integer>> set =  map.entrySet();
        
        for (Entry<String, Integer>  s : set) {
            System.out.println(s);
        }
        
    }
image.png

3.集合框架(Map集合的遍历之键找值)

4.集合框架(Map集合的遍历之键值对对象找键和值)

5.HashMap 的嵌套

//hashMap的嵌套
    public static void main(String[] args) {
        HashMap<String,Integer> map1 = new HashMap<>();
        map1.put("test1", 1);
        map1.put("test2", 2);
        map1.put("test3", 3);
        
        HashMap<String,Integer> map2 = new HashMap<>();
        map2.put("testa", 5);
        map2.put("testb", 6);
        map2.put("testc", 7);
        
        HashMap<String,HashMap<String,Integer>> tmap = new HashMap<>();
        tmap.put("map-test1",map1);
        tmap.put("map-test2",map2);
        
//      for (HashMap<String,Integer> item : tmap.keySet()) {
//          for (String string : item.keySet()) {
//              System.out.println(string);
//          }
//      }
        
        for (String string : tmap.keySet()) {
            HashMap<String,Integer> item = tmap.get(string);
            for (String string1 : item.keySet()) {
                System.out.println(item.get(string1));
            }
        }
        
    }

总结

/**
* Collection
* List(存取有序,有索引,可以重复)
* ArrayList
* 底层是数组实现的,线程不安全,查找和修改快,增和删比较慢
* LinkedList
* 底层是链表实现的,线程不安全,增和删比较快,查找和修改比较慢
* Vector
* 底层是数组实现的,线程安全的,无论增删改查都慢
* 如果查找和修改多,用ArrayList
* 如果增和删多,用LinkedList
* 如果都多,用ArrayList
* Set(存取无序,无索引,不可以重复)
* HashSet
* 底层是哈希算法实现
* LinkedHashSet
* 底层是链表实现,但是也是可以保证元素唯一,和HashSet原理一样
* TreeSet
* 底层是二叉树算法实现
* 一般在开发的时候不需要对存储的元素排序,所以在开发的时候大多用HashSet,HashSet的效率比较高
* TreeSet在面试的时候比较多,问你有几种排序方式,和几种排序方式的区别
* Map
* HashMap
* 底层是哈希算法,针对键
* LinkedHashMap
* 底层是链表,针对键
* TreeMap
* 底层是二叉树算法,针对键
* 开发中用HashMap比较多

上一篇 下一篇

猜你喜欢

热点阅读