HashMap:对于put、remove以及containsKey方法,averageTime(n)基本都是常量。
1、HashMap类的方法描述
//Constructs an empty HashMap with the specified initial capacity(初始容量) and load factor(加载因子).
public HashMap(int initialCapacity, float loadFactor);
//Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
public HashMap(int initialCapacity);
//Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
public HashMap();
//Returns true if this map maps one or more keys to the specified value.
public boolean containsValue(Object value);
//Returns <tt>true</tt> if this map contains a mapping for the specified key.
public boolean containsKey(Object key);
//HashMap中是否包含key
public V get(Object key);
//向HashMap中存入key-value
public V put(K key, V value);
//删除key和对应的value
public V remove(Object key);
此外,HashMap中还有包含有 size( )、isEmpty( )、chear( )、clone( )、toString( )、entrySet( )、keySet( )、valueSet( )等方法。
2、HashMap的实现原理(即如何做到增删改查等操作的平均时间都是常量)
散列设计:散列是将键转换成数组索引的过程。首先将给定key作为参数,通过调用hashCode( )(也被称作散列函数)得到数组的索引。键可以自己定义hashCode( ),也可以从父类继承,其中 Object类中有一版本的hashCode( ),该方法将key通过简单的计算操作返回 int 类型(称为散列值 hash value)。
即:key—>hashCode—>散列值—>某种计算—>数组索引
例如:
int hash = key.hashCode();
index = hash % table.length;
//上述直接对数组长度取余的方法对于 散列值为负数时需要调用Math.abs()方法处理,可通过更高效的方法将散列值最左边的符号位“与掉”
//0x7FFFFFFF 是使用16进制表示 int 的最大值
index = (hash % 0x7FFFFFFF) % table.length;
//HashMap中hashCode()的实现方式,异或
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//Object类中的hashCode()实现是native方法
public native int hashCode();
//String类中的hashCode()实现
public int hashCode() {
int var1 = this.hash;
if (var1 == 0 && this.value.length > 0) {
char[] var2 = this.value;
for(int var3 = 0; var3 < this.value.length; ++var3) {
var1 = 31 * var1 + var2[var3];
}
this.hash = var1;
}
return var1;
}
解决冲突