1、映射(Map)介绍
1.1、Map的用处
- 通常,我们需要知道某些键的信息,并想要查找与之对应的元素。映射用来存放键/值对
- 如果提供了键,就能够查找到值
- 例如,有一张关于员工信息的记录表,键为员工ID,值为Employee对象
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类库为映射提供了两个通用的实现:TreeMap
和HashMap
。这两个类都实现了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 aComparator
provided at map creation time, depending on which constructor is used. - 不是线程安全的
2.3、比较
HashMap
对键进行散列TreeMap
用键的整体顺序对元素进行排序,并将其组织成搜索树
散列
或比较函数
只能作用于键
。与键关联的值不能进行散列或比较散列稍微快一点;如果不需要按照排列顺序访问键,就最好选择散列
添加元素
/**
* 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、链接散列集与映射
LinkedHashSet
和LinkedHashMap
类用来记住插入元素项的顺序
。
这样就可以避免在散列表中的项从表面上是随机排列的,当条目插入到表中时,就会并入到双向链表中