import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* 简易HashMap
* 数组 + 单向链表
*/
public class MyHashMap {
private Node[] table;
private int size;
private int initCapacity = 16;
public MyHashMap() {
table = new Node[initCapacity];
}
/**
* hash表存放键值对个数
* @return
*/
public int size() {
return size;
}
/**
* hash表是否为空
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 存放键值对
* @param key
* @param value
* @return
*/
public boolean put(Object key, Object value) {
int hash = Math.abs(key.hashCode()) % initCapacity;
Node x = table[hash];
if(x == null) {
table[hash] = new Node(key, value, null);
size++;
return true;
}else {
Node n;
for(n = x; n != null; n = n.next) {
if(key.equals(n.key)) {
n.value = value;
return true;
}
x = n;
}
x.next = new Node(key, value, null);
size++;
return true;
}
}
/**
* 根据健获取值
* @param key
* @return
*/
public Object get(Object key) {
int hash = Math.abs(key.hashCode()) % initCapacity;
for(Node n = table[hash]; n != null; n = n.next) {
if(key.equals(n.key)) {
return n.value;
}
}
return null;
}
/**
* Hash迭代类
*/
class MyHashIterator{
Node next;
int index;
public MyHashIterator() {
index = 0;
next = null;
if(table != null && size > 0) {
do {
}while(index < table.length && (next = table[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
public final Node nextNode() {
Node e = next;
if((next = e.next) == null) {
do {
}while(index < table.length && (next = table[index++]) == null);
}
return e;
}
}
/**
* 返回键的Set集合
* @return
*/
public Set<Object> MykeySet() {
return new MyKeySet();
}
/**
* 键的Set类
*/
final class MyKeySet extends AbstractSet<Object>{
public Iterator<Object> iterator() {
return new MyKeyIterator();
}
public int size() {
return size;
}
}
/**
* 键的迭代类
*/
final class MyKeyIterator extends MyHashIterator implements Iterator<Object>{
public Object next() {
return nextNode().key;
}
}
/**
* 值的集合
* @return
*/
public Collection<Object> values() {
return new MyValues();
}
/**
* 值的集合类
*/
final class MyValues extends AbstractCollection<Object>{
public Iterator<Object> iterator() {
return new MyValueIterator();
}
public int size() {
return size;
}
}
/**
* 值的迭代类
*/
final class MyValueIterator extends MyHashIterator implements Iterator<Object>{
public Object next() {
return nextNode().value;
}
}
}
/**
* 节点类
*/
class Node{
Object key;
Object value;
Node next;
public Node(Object key, Object value, Node next) {
this.key = key;
this.value = value;
this.next = next;
}
}