package ds;
public class MyHashMap {
private static int length = 10;
private MyEntry[] entries;
private int index = 0;
public MyHashMap() {
super();
initinalize();
}
public void initinalize() {
entries = new MyEntry[length];
}
// 添加键值对
public String put(String key, String value) {
// 要添加到的链表的下表
int index = key.hashCode() % length;
// 链表当前存储的第一个元素
MyEntry privious = entries[index];
// 有相同的key就覆盖
for (MyEntry entry = entries[index]; entry != null; entry = entry.next) {
if (entry.getKey().equals(key)) {
// 替换value
String oldValue = entry.getValue();
entry.setValue(value);
return oldValue;
}
}
// 没有相同的key就添加,并且把这个键值对放在头部
MyEntry entry = new MyEntry(key, value);
entry.next = privious;
entries[index] = entry;
return null;
}
// 根据key取值
public String get(String key) {
// 要查找的链表的位置
int index = key.hashCode() % length;
// 在链表中查找key对应的值
for (MyEntry entry = entries[index]; entry != null; entry = entry.next) {
if (entry.key.equals(key)) {
return entry.getValue();
}
}
return null;
}
private final class MyEntry {
private String key;
private String value;
private MyEntry next;
public MyEntry() {
super();
}
public MyEntry(String key, String value) {
super();
this.key = key;
this.value = value;
}
public MyEntry(String key, String value, MyEntry next) {
super();
this.key = key;
this.value = value;
this.next = next;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public MyEntry getNext() {
return next;
}
public void setNext(MyEntry next) {
this.next = next;
}
}
}