Step1:定义节点类
public class Node2<K,V> {
int hash;
K key;
V value;
Node2 next;
}
Step2:构造主框架
package com.ysl.mycollection;
public class SxtHashMap<K,V> {
Node2[] table;
int size;
public SxtHashMap(){
}
public void put(K key,V value){
}
public V get(K key){
}
@Override
public String toString() {
}
public int myHash(int v, int length){
}
public static void main(String[] args) {
}
}
Step3:定义方法
public SxtHashMap(){
table = new Node2[16];
}
public void put(K key,V value){
Node2 newNode = new Node2();
newNode.hash = myHash(key.hashCode(),table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
Node2 temp = table[newNode.hash];
Node2 iterLast = null;
boolean keyRepeat =false;
if (temp==null){
table[newNode.hash] = newNode;
size++;
}
else {
while (temp!=null){
if(temp.key.equals(key)){
keyRepeat = true;
temp.value=value;
break;
}
else {
iterLast =temp;
temp=temp.next;
}
}
if(!keyRepeat){
iterLast.next = newNode;
size++;
}
}
}
public V get(K key){
int hash = myHash(key.hashCode(),table.length);
V value = null;
if(table[hash]!=null){
Node2 temp = table[hash];
while(temp!=null){
if(temp.key.equals(key)){
return (V)temp.value;
}
else {
temp=temp.next;
}
}
}
return value;
}
@Override
public String toString() {
StringBuilder sb =new StringBuilder();
sb.append('{');
for(int i=0;i<table.length;i++){
Node2 temp = table[i];
while (temp!=null){
sb.append(temp.key+":"+temp.value+",");
temp= temp.next;
}
}
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
}
public int myHash(int v, int length){
return v&(length-1);
}
Step3:应用
public static void main(String[] args) {
SxtHashMap<Integer,String> m = new SxtHashMap<>();
m.put(53,"aa");
m.put(69,"bb");
m.put(85,"cc");
System.out.println(m);
System.out.println(m.get(53));
}
Step4:示例
