”最近一场编程比赛,让我对自己Java基础知识的薄弱触目惊心。为了悲剧不在重演,我决定痛定思痛,从力扣题库开始,用自己的视角,记录所有的改变。“
题目本身很简单,网上对于思路的分析有一大堆,关键的一点就是使用哈希表以O(n)的时间复杂度解决问题。就我自己而言,平时对于HashMap的使用很少,故将学习过程记录于此。
HashMap:
1.是什么:
HashMap的实现是以数组为主体,链表为辅助的组合。数组的采用保证了随机访问时时间复杂度为O(1),链表的配合解决了发生Hash冲突时,冲突元素能作为冲突位置的next数据被保存起来。
2.Java中是对于数组的节点元素的定义如下:
HashMap中的内部类--Node,实现的是Map.Entry接口,具体代码如下:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
HashMap最核心的是hashcode生成算法
Objects.hashCode(key) ^ Objects.hashCode(value);
这里面的Object.hashCode是一个native方法。
下面这个方法,是计算hash值的方法:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
通过key值去计算,然后将得到的hashcode与它右移16位的结果