哈希表中哈希函数的实现步骤大概如下
Public int hash(Object key){
return hash_code(key) % table.length;
}
为了提高效率,可以使用&位运算取代%运算【前提:将数组的长度设计为2的幂(2^n)】
Public int hash(Object key){
return hash_code(key) & (table.length - 1);
}
良好的哈希函数
public static int hashCode(int value){
return value;
}
public static int hashCode(float value){
return floatToIntBits(value);
}
public static int hashCode(long value){
return (int)(value ^ (value >>> 32));
}
public static int hashCode(double value){
long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
>>>和^的作用是?
String string = "jack";
int hashCode = 0;
int len = string.length;
for(int i = 0; i < len; i++){
char c = string.charAt(i);
hashCode = 31 * hashCode + c;
}
String string = "jack";
int hashCode = 0;
int len = string.length;
for(int i = 0; i < len; i++){
char c = string.charAt(i);
hashCode = (hashCode << 5) - hasCode + c;
}
public class Person implements Comparable<Person> {
private int age; // 10 20
private float height; // 1.55 1.67
private String name; // "jack" "rose"
public Person(int age, float height, String name) {
this.age = age;
this.height = height;
this.name = name;
}
@Override
/**
* 用来比较2个对象是否相等
*/
public boolean equals(Object obj) {
// 内存地址
if (this == obj) return true;
if (obj == null || obj.getClass() != getClass()) return false;
// if (obj == null || !(obj instanceof Person)) return false;
// 比较成员变量
Person person = (Person) obj;
return person.age == age
&& person.height == height
&& (person.name == null ? name == null : person.name.equals(name));
}
@Override
public int hashCode() {
int hashCode = Integer.hashCode(age);
hashCode = hashCode * 31 + Float.hashCode(height);
hashCode = hashCode * 31 + (name != null ? name.hashCode() : 0);
return hashCode;
}
@Override
public int compareTo(Person o) {
return age - o.age;
}
}
private int hash(K key){
if(key == null){
return 0;
}
int h = key.hashCode();
return (h ^ (h >>> 16)) & (table.length - 1);
}
LinkedHashMap – 删除注意点
// 交换prev
LinkedNode<K, V> tmp = node1.prev;
node1.prev = node2.prev;
node2.prev = tmp;
if (node1.prev == null) {
first = node1;
} else {
node1.prev.next = node1;
}
if (node2.prev == null) {
first = node2;
} else {
node2.prev.next = node2;
}
// 交换next
tmp = node1.next;
node1.next = node2.next;
node2.next = tmp;
if (node1.next == null) {
last = node1;
} else {
node1.next.prev = node1;
}
if (node2.next == null) {
last = node2;
} else {
node2.next.prev = node2;
}
原文:https://www.cnblogs.com/coderD/p/14673913.html