Map映射

1、映射(Map)介绍

1.1、Map的用处

  • 通常,我们需要知道某些键的信息,并想要查找与之对应的元素。映射用来存放键/值对
  • 如果提供了键,就能够查找到值
  • 例如,有一张关于员工信息的记录表,键为员工ID,值为Employee对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DonQuOob-1580979007672)(images/15.png)]

1.2、JDK中Map接口

// <K> the type of keys maintained by this map
//  <V> the type of mapped values
public interface Map<K,V> {
 	
    //常用的方法
    int size();
    	
    boolean isEmpty();
    
    boolean containsKey(Object key);

    boolean containsValue(Object value);
	  
    V get(Object key);
    	  
    V put(K key, V value);
    
    V remove(Object key);
	
    // Bulk Operations
    void putAll(Map<? extends K, ? extends V> m);
    void clear();
    
    // Views:视图
    Set<K> keySet();//@return a set view of the keys contained in this map
    Collection<V> values();//return a collection view of the values contained in this map
	Set<Map.Entry<K, V>> entrySet();//a set view of the mappings contained in this map
    
    //A map entry (key-value pair). 
    //The Map.entrySet  method returns a collection-view of the map, whose elements are of this class.
    interface Entry<K,V> {
         K getKey();
         V getValue();
        V setValue(V value);
    }
    
     default V getOrDefault(Object key, V defaultValue) 
         
     default V replace(K key, V value) 
    
}

1.2、Map特点

  • An object that maps keys to values.

  • 一个Map不能包含重复的键;每个键至多映射一个值。

  • 这个接口相当于字典

  • 这个接口提供三种视图;这允许一个map的内容可以被看做 键的集合,值的集合key-value的映射集

  • 一些Map确保他们的顺序例如TreeMap;而另外一些不确保顺序例如HashMap

  • 通常提供两种构造器:包含参数的构造器;不包含参数的构造器

  • 在Map上调用不存在的方法通常会抛出UnsupportedOperationException异常

2、基本映射操作

Java类库为映射提供了两个通用的实现:TreeMapHashMap。这两个类都实现了Map接口

2.1、HashMap

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    
 	//构造器
    public HashMap(int initialCapacity, float loadFactor) {}
    public HashMap(int initialCapacity){}
    public HashMap() {}  // Constructs an empty HashMap with the default initial capacity 16) and the default load factor (0.75).
    public HashMap(Map<? extends K, ? extends V> m) //
    
    //添加元素
     public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    //hash方法
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
}
  • HashMap基于Map接口

  • 提供所有map的可选操作,并且允许空值空键

  • HashMap大致等于HashTable😭HashTale是同步的并且不允许为空)

  • 同时这个类也不保证map的顺序

  • 不要设置初始的HashMap容量太大或者负载因子太小

  • 有两个参数影响HashMap:initial Capacity(初始容量)load factor(装载因子)

    initial Capacity:哈希表被创建时哈希表中桶的初始化大小

    load factor:决定合适hashMap需要再次进行哈希

  • 通常情况下load factor(负载因子)的大小为0.75

  • 假如在Hash表中存入许多实例,需要保证足够大的初始容量;从而保证mapping存储元素更加有效

  • 线程不安全

2.2、TreeMap

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable {
    
    //比较器;用来存放键
     private final Comparator<? super K> comparator;

    private transient Entry<K,V> root = null;
    
    //构造器
     public TreeMap()//Constructs a new, empty tree map, using the natural ordering of its keys.  All keys inserted into the map must implement the  Comparable} interface.
    
      public TreeMap(Comparator<? super K> comparator)
    

}

  • TreeMap是基于NavigableMap红黑树实现
  • The map is sorted according to the Comparable of its keys , or by a Comparator provided at map creation time, depending on which constructor is used.
  • 不是线程安全的

2.3、比较

  1. HashMap对键进行散列
  2. TreeMap用键的整体顺序对元素进行排序,并将其组织成搜索树
  3. 散列比较函数只能作用于与键关联的值不能进行散列比较
  4. 散列稍微快一点;如果不需要按照排列顺序访问键,就最好选择散列

添加元素

 /**
     * Associates the specified value with the specified key in this map
     * (optional operation).  If the map previously contained a mapping for
     * the key, the old value is replaced by the specified value.  (A map
     * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
     * if {@link #containsKey(Object) m.containsKey(k)} would return
     * <tt>true</tt>.)
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>,
     *         if the implementation supports <tt>null</tt> values.)
     * @throws UnsupportedOperationException if the <tt>put</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     * @throws NullPointerException if the specified key or value is null
     *         and this map does not permit null keys or values
     * @throws IllegalArgumentException if some property of the specified key
     *         or value prevents it from being stored in this map
     */
    V put(K key, V value);

检索元素

 /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>If this map permits null values, then a return value of
     * {@code null} does not <i>necessarily</i> indicate that the map
     * contains no mapping for the key; it's also possible that the map
     * explicitly maps the key to {@code null}.  The {@link #containsKey
     * containsKey} operation may be used to distinguish these two cases.
     *
     * @param key the key whose associated value is to be returned
     * @return the value to which the specified key is mapped, or
     *         {@code null} if this map contains no mapping for the key
     * @throws ClassCastException if the key is of an inappropriate type for
     *         this map
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified key is null and this map
     *         does not permit null keys
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     */
    V get(Object key);
  • 键必须是唯一的;不能对同一个键存放两个值;如果对同一个键两次调用put方法,第二个值就会取代第一个值
  • remove方法用于从映射中删除给定键对应的元素
  • containsKey(Object Key)

3、映射视图

集合框架不认为映射本身是一个集合(其他数据结构框架认为映射是一个键/值对集合,或者是由键索引的值集合)

不过,可以得到映射的视图(view)-----这是实现了Collection接口或某个子接口的对象

有3种视图:键集值集合(不是一个集)以及键/值对集

下面的方法,会返回这3个视图(条目集的元素是实现了Map.Entry接口的类的对象)

Set<K> keySet(); // return a set view of the keys contained in this map


//返回映射中所有值的一个集合视图。
//可以从这个集合中删除元素,所删除的值级相应的键将从映射中删除,不过不能增加元素
Collection<V> values();// a collection view of the values contained in this map

//返回Map.Entry对象(映射中的键/值对)的一个集视图。
//可以从这个集中删除元素,他们将从映射中删除,但是不能增加任何元素
Set<Map.Entry<K, V>> entrySet();// return a set view of the mappings contained in this map
		
		
		K getKey();  // Returns the key corresponding to this entry.
		
         
		V getValue();//Returns the value corresponding to this entry.
		
		V setValue(V value);

4、链接散列集与映射

LinkedHashSetLinkedHashMap类用来记住插入元素项的顺序

这样就可以避免在散列表中的项从表面上是随机排列的,当条目插入到表中时,就会并入到双向链表中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KNkXq04L-1580979007689)(images/16.png)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值