Java 代码、以线性探测法和链地址法处理冲突创建哈希表
时间: 2024-04-21 07:23:30 浏览: 129
哈希表,开放地址法之线性探测代码(JAVA)
你好!以下是使用线性探测法和链地址法处理冲突创建哈希表的Java代码示例:
1. 使用线性探测法处理冲突的哈希表:
```java
class LinearProbingHashTable {
private static final int DEFAULT_SIZE = 10;
private Entry[] table;
private int size;
public LinearProbingHashTable() {
table = new Entry[DEFAULT_SIZE];
size = 0;
}
public void put(int key, String value) {
Entry entry = new Entry(key, value);
int index = hash(key);
while (table[index] != null && table[index].getKey() != key) {
index = (index + 1) % table.length; // 线性探测法
}
table[index] = entry;
size++;
}
public String get(int key) {
int index = hash(key);
while (table[index] != null && table[index].getKey() != key) {
index = (index + 1) % table.length; // 线性探测法
}
if (table[index] != null) {
return table[index].getValue();
}
return null;
}
private int hash(int key) {
return key % table.length;
}
private static class Entry {
private final int key;
private final String value;
public Entry(int key, String value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
}
}
```
2. 使用链地址法处理冲突的哈希表:
```java
import java.util.LinkedList;
class ChainingHashTable {
private static final int DEFAULT_SIZE = 10;
private LinkedList<Entry>[] table;
private int size;
public ChainingHashTable() {
table = new LinkedList[DEFAULT_SIZE];
size = 0;
}
public void put(int key, String value) {
Entry entry = new Entry(key, value);
int index = hash(key);
if (table[index] == null) {
table[index] = new LinkedList<>();
}
LinkedList<Entry> chain = table[index];
for (Entry e : chain) {
if (e.getKey() == key) {
e.setValue(value);
return;
}
}
chain.add(entry);
size++;
}
public String get(int key) {
int index = hash(key);
if (table[index] != null) {
LinkedList<Entry> chain = table[index];
for (Entry e : chain) {
if (e.getKey() == key) {
return e.getValue();
}
}
}
return null;
}
private int hash(int key) {
return key % table.length;
}
private static class Entry {
private final int key;
private String value;
public Entry(int key, String value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
```
这是创建哈希表的基本示例,你可以根据自己的需求进行修改和扩展。希望对你有所帮助!如有更多问题,请随时提问。
阅读全文