package mycollection;
public class TestHashMap4<K,V> {
Node3<K,V>[] table;
int size;
public TestHashMap4() {
table = new Node3[16];
}
public void remove(K key){
Node3<K,V> up;
Node3<K, V> down;
Node3<K, V> temp;
int x = 0;
int hash = myHash(key.hashCode(), table.length);
temp = table[hash];
up = temp;
while(temp != null){
++x;
down = temp.next;
if(temp.key.equals(key)){
if(x == 1){
table[hash] = temp.next;
break;
}else{
up.next = down;
break;
}
}else{
up = temp;
temp = down;
}
}
}
@SuppressWarnings("unchecked")
public V get(K key) {
int hash = myHash(key.hashCode(), table.length);
Object value = null;
if(table[hash] != null){
Node3<K,V> temp = table[hash];
while(temp != null){
if(temp.key.equals(key)){
value = temp.value;
break;
}else{
temp = temp.next;
}
}
}
return (V)value;
}
public void put(K key,V value) {
int x = 0;
if(x >= (0.75*table.length)){
Node3<K, V>[] newtable = new Node3[table.length<<1];
table = newtable;
}
Node3<K,V> newNode = new Node3<>();
newNode.hash = myHash(key.hashCode(), table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
Node3<K,V> temp = table[newNode.hash];
Node3<K,V> iterLast = null;
boolean keyRepeat = false;
if(temp == null){
table[newNode.hash] = newNode;
size++;
x++;
}else{
while(temp != null){
if(temp.equals(key)){
keyRepeat = true;
temp.value = value;
break;
}else{
iterLast = temp;
temp = temp.next;
}
}
if(!keyRepeat){
iterLast.next = newNode;
size++;
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
for(int i = 0; i<table.length; i++){
Node3 temp = table[i];
while(temp != null) {
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
sb.setCharAt(sb.length()-1, '}');
return sb.toString();
}
public static int myHash(int v,int length){
return v&(length-1);
}
public static void main(String[] args) {
TestHashMap4<Integer,String> m = new TestHashMap4<>();
m.put(10, "a");
m.put(20, "b");
m.put(30, "c");
m.put(10, "666");
m.put(53, "d");
m.put(69, "e");
m.put(85, "f");
System.out.println(m);
System.out.println(m.get(69));
m.remove(69);
System.out.println(m);
}
}
}
package mycollection;
public class Node3<K,V> {
int hash;
K key;
V value;
Node3 next;```