节点
public class Node<T, V> {
T key;
V value;
Node<T, V> next;
public Node(T key, V value) {
this.key=key;
this.value = value;
}
public Node() {
}
}
链表
package shoudongshixianHashMap;
public class Link<T, V> {
private Node<T, V> head;
public Link(Node<T, V> node) {
this.head = node;
head.next = null;
}
public Link() {
this(new Node<>());
}
public void insert(T key, V value) {
Node<T, V> tempNode = find(key);
if (tempNode != null) {
tempNode.value = value;
} else {
Node<T, V> node = new Node<>(key, value);
node.next = head.next;
head.next = node;
}
}
public Node<T, V> find(T key) {
Node<T, V> parent = findParent(key);
if (parent == null) {
return null;
} else {
return parent.next;
}
}
public boolean delete(T key) {
Node<T, V> parent = findParent(key);
if (parent == null) {
return false;
}
parent.next = parent.next.next;
return true;
}
public boolean update(T key, V newValue) {
Node<T, V> parent = findParent(key);
if (parent == null) {
return false;
}
parent.next.value = newValue;
return true;
}
private Node<T, V> findParent(T key) {
if (head == null) {
return null;
}
Node<T, V> node = head.next;
Node<T, V> parent = head;
while (node != null) {
if (node.key == key) {
return parent;
}
parent = node;
node = node.next;
}
return null;
}
public Node<T, V> getHead() {
return head;
}
}
表的实现
public boolean delete(T key) {
return this.map[getIndex(key)].delete(key);
}
public boolean update(T key, V value) {
return this.map[getIndex(key)].update(key, value);
}
public Integer getIndex(T key) {
return key.hashCode() % size;
}
public Link<T, V>[] getMap() {
return map;
}
}
|