HashMap类详解

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;
}

解决冲突

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值