帮我用java实现一个哈希表,哈希表内存储静态类
时间: 2023-08-14 18:25:31 浏览: 42
好的,下面是一个简单的基于Java的哈希表实现,其中存储了一个静态类 `MyClass`:
```java
public class MyHashTable {
private static final int TABLE_SIZE = 10;
private Entry[] table;
public MyHashTable() {
table = new Entry[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = null;
}
}
public MyClass get(String key) {
int hash = (key.hashCode() % TABLE_SIZE);
if (table[hash] == null) {
return null;
} else {
Entry entry = table[hash];
while (entry != null && !entry.key.equals(key)) {
entry = entry.next;
}
if (entry == null) {
return null;
} else {
return entry.value;
}
}
}
public void put(String key, MyClass value) {
int hash = (key.hashCode() % TABLE_SIZE);
if (table[hash] == null) {
table[hash] = new Entry(key, value);
} else {
Entry entry = table[hash];
while (entry.next != null && !entry.key.equals(key)) {
entry = entry.next;
}
if (entry.key.equals(key)) {
entry.value = value;
} else {
entry.next = new Entry(key, value);
}
}
}
private static class Entry {
String key;
MyClass value;
Entry next;
public Entry(String key, MyClass value) {
this.key = key;
this.value = value;
this.next = null;
}
}
private static class MyClass {
String name;
int age;
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "MyClass[name=" + name + ", age=" + age + "]";
}
}
}
```
在这个例子中,我们定义了一个 `MyHashTable` 类,其中存储了一个静态类 `MyClass`。哈希表的实现使用了链表来解决哈希冲突的问题。具体来说,每个哈希桶(即哈希表中的一个元素)存储了一个指向链表头的指针,如果多个键被映射到同一个哈希桶中,它们会被存储在同一个链表中。在查找键对应的值时,我们先计算键的哈希值,然后在对应的哈希桶中查找链表,直到找到对应的键为止。在插入键值对时,我们也是先计算键的哈希值,然后在对应的哈希桶中查找链表,如果找到了对应的键,就更新它的值;如果没有找到,就在链表末尾插入一个新的节点。