package test;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
public class HashMap<K, V> {
Node<K, V>[] table;//链表数组 存储结构
@SuppressWarnings("unchecked")
public HashMap() {
table = new Node[10];
}
//根据key计算数组下标 如果数组该下标已存在元素 则改为存该元素 并将该元素的next指向原元素
public Node<K, V> put(K key, V value) {
Node<K, V> node;
if ((node = this.getNode(key)) != null) {
node.value = value;
} else {
Node<K, V> newNode = new Node<K, V>(key, value);
node = table[hash(key)];
newNode.next = node;
table[hash(key)] = newNode;
node = newNode;
}
return node;
}
//根据key计算数组下标 再遍历链表找到相应的key对应的value
public Node<K, V> getNode(K key) {
Node<K, V> node = this.table[hash(key)];
if (node != null) {
if (node.key.equals(key)) {
return node;
} else {
while ((node = node.next) != null) {
if (node.key.equals(key)) {
return node;
}
}
}
}
return node;
}
public V get(K key) {
Node<K, V> node = this.getNode(key);
return node == null ? null : node.value;
}
public int hash(K key) {
int hashcode = key.hashCode() % 10;
return hashcode;
}
//链表节点内部类
@SuppressWarnings("hiding")
class Node<K, V> {
Node<K, V> next;
K key;
V value;
public Node(K key, V value) {
// System.out.println("hash node ...");
this.key = key;
this.value = value;
}
}
//key set 内部类 维护key值
final class HashMapKeySet extends AbstractSet<K> {
public final Iterator<K> iterator() {
return new HashMapKeyIterator();
}
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
}
//实际管理key值得迭代器 按数组下标顺序遍历节点
final class HashMapKeyIterator implements Iterator<K> {
private int index = 0;
private Node<K, V> node = null;
@Override
public boolean hasNext() {
if (node != null) {
node = node.next;
while (node == null && index < table.length - 1) {
index++;
node = table[index];
}
} else {
node = table[index];
while (node == null && index < table.length - 1) {
index++;
node = table[index];
}
}
return node != null;
}
@Override
public K next() {
return node.key;
}
}
public Set<K> keySet() {
return new HashMapKeySet();
}
public static void main(String args[]) {
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 100; i++) {
map.put(i + "", "a");
}
for (String key : map.keySet()) {
System.out.println(key + "==>" + map.get(key));
}
System.out.println("##################");
map.put("1", "c");
map.put("4", "d");
for (String key : map.keySet()) {
System.out.println(key + "==>" + map.get(key));
}
}
}