Node3类
package cn.sxt.myCollection;
/*
* to be used in SxtHashMap
*/
public class Node3<K,V> {
int hash;
K key;
V value;
Node3 next;
}
SxtHashMap04类
package cn.sxt.myCollection;
import java.security.KeyRep;
/*
* Define a HashMap
* implement get method
*/
public class SxtHashMap04<K, V>{
Node3[] table; //bucket array
int size; //the number of key-value
public SxtHashMap04() {
table = new Node3[16]; //the length is integer power of 2
}
public V get(K key) {
int hash = myHash(key.hashCode(), table.length);
V value = null;
if (table[hash] != null) {
Node3 temp = table[hash];
while(temp != null){
if(temp.key.equals(key)){//if equals, return value
value = (V)temp.value;
break;
}else {
temp = temp.next;
}
}
}
return value;
}
public void put(K key, V value){
//define the new node obejct
Node3 newNode = new Node3();
newNode.hash = myHash(key.hashCode(), table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
Node3 temp = table[newNode.hash];
Node3 iterLast = null;//to record the last element that traversed
if(temp == null){
//array is null and put new Node into table
table[newNode.hash] = newNode;
size++;
}else{
//if array is not null, traverse corresponding list.
while(temp != null){
//while key is repeated
if(temp.key.equals(key)){
temp.value = value;// only need to cover value, others(hash, key, next) do not need to be changed.
return;
}else{
//while key is not repeated, then traverse next
iterLast = temp;
temp = temp.next;
}
}
iterLast.next = newNode;
size++;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
//traverse bucket array
for (int i = 0; i < table.length; i++) {
Node3 temp = table[i];
//traverse the list
while(temp != null){
sb.append(temp.key + ":" + temp.value + ",");
temp = temp.next;
}
}
sb.setCharAt(sb.length() - 1, '}');
return sb.toString();
}
public static void main(String[] args) {
SxtHashMap04<Integer, String> m = new SxtHashMap04();
m.put(1, "aa");
m.put(2, "bb");
m.put(3, "cc");
m.put(2, "ssss");
System.out.println(m);
System.out.println(m.get(1));
System.out.println(m.get(5));
}
public int myHash(int v, int length){
return v&(length - 1);
}
}
运行结果:
{1:aa,2:ssss,3:cc}
aa
null