hashcode怎么写
时间: 2023-09-13 12:11:27 浏览: 45
在 Java 中,一个对象的哈希码(hashcode)可以通过重载 `hashCode()` 方法来实现。通常情况下,我们会根据对象的属性计算出一个唯一的哈希值。
以下是一个示例代码:
```java
public class MyClass {
private int id;
private String name;
// 构造方法和其他方法
@Override
public int hashCode() {
int result = 17;
result = 31 * result + id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
```
在上面的代码中,我们使用了经典的哈希算法,即将一个初始值(这里是 17)乘以一个质数(这里是 31),然后加上属性的哈希值。这样可以确保不同的属性组合生成的哈希值不同。
需要注意的是,在重载 `hashCode()` 方法时,还需要同时重载 `equals()` 方法,以确保对象的相等判断是正确的。
相关问题
重写hashCode
当你想要重写 `hashCode` 方法时,你应该遵循以下准则:
1. 如果两个对象相等,则它们的 `hashCode` 值必须相等。
2. 如果两个对象不相等,则它们的 `hashCode` 值可能相等。
为了实现这些准则,你可以使用对象中用于比较对象相等性的域来计算 `hashCode` 值。例如,如果你有一个类叫做 `Person`,它有一个 `name` 域和一个 `age` 域,你可以这样写 `hashCode` 方法:
```
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
```
上面的代码使用了 `name` 域的 `hashCode` 方法和 `age` 域的值来计算整个对象的 `hashCode` 值。
注意:在这里使用的是 31 乘以结果加上域的值,是为了让不同的域有不同的贡献,防止hash冲突
另外需要注意的是,如果你重写了 `hashCode` 方法,你也应该重写 `equals` 方法,以确保它们遵循相等性的准则。
手写hashmap
好的,这里是一个简单的手写hashmap的实现:
```java
public class MyHashMap<K, V> {
private int size;
private int capacity;
private Node<K, V>[] table;
private static class Node<K, V> {
final K key;
V value;
Node<K, V> next;
Node(K key, V value, Node<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
public MyHashMap(int capacity) {
this.size = 0;
this.capacity = capacity;
this.table = new Node[capacity];
}
public V get(K key) {
int index = hash(key);
Node<K, V> node = table[index];
while (node != null) {
if (node.key.equals(key)) {
return node.value;
}
node = node.next;
}
return null;
}
public void put(K key, V value) {
int index = hash(key);
Node<K, V> node = table[index];
while (node != null) {
if (node.key.equals(key)) {
node.value = value;
return;
}
node = node.next;
}
// If the key does not exist in the map, add a new node to the front of the list at the index.
Node<K, V> newNode = new Node<>(key, value, table[index]);
table[index] = newNode;
size++;
// If the map has exceeded its load factor, resize the table.
if (size > capacity * 0.75) {
resize();
}
}
public void remove(K key) {
int index = hash(key);
Node<K, V> node = table[index];
Node<K, V> prev = null;
while (node != null) {
if (node.key.equals(key)) {
if (prev == null) {
table[index] = node.next;
} else {
prev.next = node.next;
}
size--;
return;
}
prev = node;
node = node.next;
}
}
private int hash(K key) {
return key.hashCode() % capacity;
}
private void resize() {
capacity *= 2;
Node<K, V>[] newTable = new Node[capacity];
for (Node<K, V> node : table) {
while (node != null) {
Node<K, V> next = node.next;
int index = hash(node.key);
node.next = newTable[index];
newTable[index] = node;
node = next;
}
}
table = newTable;
}
}
```
这个HashMap使用链表来解决冲突,并且在size超过capacity*0.75时会自动扩容。