此實現僅僅是爲了實現筆試題的東西,沒必要深究
一、鏈表
package com.java.demo.map;
/**
* @ClassName: Entry
* @Description:
* @author weiyb
* @date 2017年9月28日 下午4:54:44
* @param <K>
* @param <V>
*/
public class Entry<K, V> {
private K k;
private V v;
private Entry<K, V> next;
public Entry() {
super();
}
public Entry(K k, V v) {
super();
this.k = k;
this.v = v;
}
public K getK() {
return k;
}
public void setK(K k) {
this.k = k;
}
public V getV() {
return v;
}
public void setV(V v) {
this.v = v;
}
public Entry<K, V> getNext() {
return next;
}
public void setNext(Entry<K, V> next) {
this.next = next;
}
}
二、map類
package com.java.demo.map;
/**
* @ClassName: MapModel
* @Description:
* @author weiyb
* @date 2017年9月28日 下午4:54:49
* @param <K>
* @param <V>
*/
public class MapModel<K, V> {
/**
* 數組長度
* @author weiyb
*/
private final int length = 100;
private Entry<K, V>[] entrys = new Entry[length];
/**
* 錄入
* @param k
* @param v
* @author weiyb
*/
public void put(K k, V v) {
int index = hash(k.hashCode());
Entry<K, V> tmp = entrys[index];
if (tmp != null) {
while (tmp.getNext() != null && !k.equals(tmp.getNext().getK())) {
tmp = tmp.getNext();
}
tmp.setNext(new Entry<K, V>(k, v));
} else {
entrys[index] = new Entry<K, V>(k, v);
}
}
/**
* 獲取
* @param k
* @return
* @author weiyb
*/
public V get(K k) {
Entry<K, V> result = new Entry<K, V>();
int index = hash(k.hashCode());
Entry<K, V> tmp = entrys[index];
if (!k.equals(tmp.getK())) {
while (tmp.getNext() != null && !k.equals(tmp.getNext().getK())) {
tmp = tmp.getNext();
}
if (tmp.getNext() != null) {
result = tmp.getNext();
}
} else {
result = tmp;
}
return result.getV();
}
private int hash(int h) {
return h % length;
}
}
三、測試
package com.java.demo.map;
import org.junit.Test;
/**
* @ClassName: MapTest
* @Description:
* @author weiyb
* @date 2017年9月27日 下午5:39:44
*/
public class MapTest {
@Test
public void mapTest() {
MapModel<String, Object> map = new MapModel<>();
for (int i = 0; i < 500; i++) {
map.put(i + "", 1000 + i);
}
for (int i = 0; i < 500; i++) {
System.out.println(map.get(i + ""));
}
}
}