哈希表数据结构JAVA实现
时间: 2024-03-18 17:36:04 浏览: 25
以下是哈希表数据结构的JAVA实现示例:
```java
import java.util.LinkedList;
public class HashTable {
private LinkedList<Entry>[] table;
private int capacity;
public HashTable(int capacity) {
this.capacity = capacity;
table = new LinkedList[capacity];
for (int i = 0; i < capacity; i++) {
table[i] = new LinkedList<>();
}
}
public void put(String key, int value) {
int index = hash(key);
LinkedList<Entry> list = table[index];
for (Entry entry : list) {
if (entry.getKey().equals(key)) {
entry.setValue(value);
return;
}
}
list.add(new Entry(key, value));
}
public int get(String key) {
int index = hash(key);
LinkedList<Entry> list = table[index];
for (Entry entry : list) {
if (entry.getKey().equals(key)) {
return entry.getValue();
}
}
return -1; // Key not found
}
private int hash(String key) {
int hashCode = key.hashCode();
return Math.abs(hashCode) % capacity;
}
private class Entry {
private String key;
private int value;
public Entry(String key, int value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}
```
使用示例:
```java
HashTable hashTable = new HashTable(10);
hashTable.put("apple", 5);
hashTable.put("banana", 10);
hashTable.put("orange", 8);
int value = hashTable.get("banana");
System.out.println(value); // 输出:10
```