1.hashMap类
2.链表节点实体类:
3.测试类:
package hashMap;
import java.util.LinkedList;
public class LvHashMap<K,V> {
LinkedList[] buckets;//桶数组, 元素类型是链表
int bucketCount;
LvHashMap(int bucketCount)
{
this.bucketCount = bucketCount;
buckets = new LinkedList[bucketCount];
for(int i = 0; i <= bucketCount - 1; i++)
{
LinkedList<Pair> l = new LinkedList<Pair>();
buckets[i] = l;
}
}
public void put(K key, V value)
{
int hashCode = key.hashCode();
int index = hashCode % bucketCount;
for(int i = 0; i <= buckets[index].size() - 1; i++)
{
if(((Pair) buckets[index].get(i)).getKey() == key)
{
((Pair) buckets[index].get(i)).setValue(value);
return;
}
}
buckets[index].add(new Pair(key, value));
}
public V get(K key)
{
int hashCode = key.hashCode();
int index = hashCode % bucketCount;
for(int i = 0; i <= buckets[index].size() - 1; i++)
{
if(((Pair) buckets[index].get(i)).getKey() == key)
{
return (V) ((Pair) buckets[index].get(i)).getValue();
}
}
return null;
}
}
2.链表节点实体类:
package hashMap;
public class Pair {
Object key;
Object value;
Pair(Object key, Object value)
{
this.key = key;
this.value = value;
}
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
3.测试类:
package hashMap;
public class HashTestDemo
{
public static void main(String[] args){
LvHashMap<String, String> hashMap = new LvHashMap<String, String>(32);
hashMap.put("key", "value");
hashMap.put("key", "value2");
System.out.println(hashMap.get("key"));
LvHashMap<String, Object> hashMap2 = new LvHashMap<String, Object>(32);
int[] array1 = {1, 2, 3, 4, 5, 6};
hashMap2.put("key", array1);
System.out.println(hashMap2.get("key") == array1);
}
}