HashMap是结合队列和链表各自的优点,创造的一种在查询和修改间取得性能平衡的一种集合!
MyMap接口:
package self;
//接口
public interface MyMap {
public void put(Object key, Object value);
public Object get(Object key);
}
此处只实现了最常用的get和put方法。
HashMap实现:
package self;
//接口实现类
public class MyHashMap implements MyMap {
private Node[] table;// 存放map数组
private int initSize;// map默认初始大小;
public MyHashMap(int initSize) {
this.initSize = initSize;
this.table = new Node[initSize];// 创建对象时初始化大小
}
@Override
public Object get(Object key) {
int i = this.indexOf(key);
Node node = this.table[i];
Object compareKey = node.getKey();
while (!key.equals(compareKey)) {
node = node.nextNode;
if (node == null) {
break;
} else {
compareKey = node.getKey();
}
}
if (node != null) {
return node.getValue();
}
return null;
}
@Override
public void put(Object key, Object value) {
int i = this.indexOf(key);
Node thisNode = new Node(key, value);
if (table[i] != null) {
Node node = table[i];
Node next = node.nextNode;// node 关联的下一个node
for (; next != null;) {
node = next;
next = node.nextNode;
}
node.setNextNode(thisNode);
} else {
table[i] = thisNode;
}
}
// 计算下标位置
private int indexOf(Object key) {
if (key != null) {
return key.hashCode() % this.initSize;// hascode值除map大小取余
}
return 0;
}
// 内部类:map节点
private class Node {
private Object key;
private Object value;
private Node nextNode;// 指向的下一个节点
public Node(Object key, Object value) {
this.key = key;
this.value = value;
}
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
}
1、采用最简单的: hash / length 取余的方式去计算应存放的下标;(仅测试,实际java源码中的计算方式复杂的多)
2、数组中存放的为Node对象,node.nextNode属性指向下一个对象;(同下标的数据通过此链表指向关联)
测试类:
package self;
import java.util.Date;
public class Test {
public static void main(String[] args) {
MyHashMap hashMap = new MyHashMap(3);
hashMap.put("1", "111");
hashMap.put("2", "222");
hashMap.put(3, 333);
hashMap.put("4", "444");
hashMap.put("a", "aaa");
hashMap.put("b", "bbb");
hashMap.put("c", "ccc");
hashMap.put("d", "ddd");
System.out.println(hashMap.get(3));
}
}