package map;
import java.util.LinkedList;
/**
* 步骤: 1:定义一个链表数组 。
* 2:写put方法,获取key的hashCode%数组长度。 判断hashcode对应的数组下标对应的linkedList是否为空,
* 如果为空就创建一个一个链表 把key、 value放入linkedList中,再把linkedList放入数组。如果不为空就要判断hashCode是否冲突,遍历hashCode下标相同的数组的链表,寻找key相同的节点,
* 如果key相同,就进行覆盖。然后return; 如果没有相同的key 就直接把entity加入linkedList中。
* 3:写get方法,获取key的hashCode%数组长度,判断数组元素是否为空,不为空就进行链表遍历找出key相同的entity,返回value即可
*
*/
public class MyHashMap {
private final static int LENGTH = 100;
LinkedList[] arr = new LinkedList[LENGTH];
@SuppressWarnings("unchecked")
public void put(Object key ,Object value){
Entity entity = new Entity(key, value) ;
int hashCode = key.hashCode()%LENGTH;
if(arr[hashCode] == null){
LinkedList<Entity> list = new LinkedList<Entity>() ;
list.add(entity);
arr[hashCode] = list ;
}else{
for (int i = 0; i < arr[hashCode].size(); i++) {
Entity e = (Entity) arr[hashCode].get(i);
if(e.getKey().equals(key)){
e.setValue(value);
return ;
}
}
arr[hashCode].add(entity);
}
}
public Object get(Object key){
int hashCode = key.hashCode()%LENGTH ;
if(arr[hashCode] != null){
for (int i = 0; i < arr[hashCode].size(); i++) {
Entity e = (Entity) arr[hashCode].get(i);
if(e.getKey().equals(key)){
return e.getValue();
}
}
}
return null;
}
public static void main(String[] args) {
MyHashMap map = new MyHashMap();
map.put("z", new Integer(2));
map.put("s", new Integer(3));
map.put("t", new Integer(4));
Integer a = (Integer) map.get("s");
Integer c = (Integer) map.get("z");
Integer b = (Integer) map.get("t");
System.out.println(a+"\t"+c+"\t"+b);
}
}
class Entity{
private Object key;
private Object value ;
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Entity(Object key, Object value) {
super();
this.key = key;
this.value = value;
}
}