衝突-解決-開雜湊/雜湊桶模擬Map集合
阿新 • • 發佈:2021-02-07
class MyHashMap {
//節點
static class Node{
private int key;
private int value;
private Node next;
public Node() {
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
int size=0;
Node []a=new Node[10];
/** Initialize your data structure here. */
public MyHashMap() {
}
/** value will always be non-negative. */
public void put(int key, int value) {
if (size/a.length>0.75)
resize ();
Node temp=new Node(key,value);
int index=key%a.length;
Node cur=a[index];
while(cur!=null){
if(cur.getKey()==key){
cur.setValue(value);
return ;
}
}
temp.setNext(a[index]);
a[index]=temp;
size++;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
int index=key%a.length;
Node cur=a[index];
while(cur!=null){
if(cur.getKey()==key)
return cur.getValue();
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int index=key%a.length;
Node cur=a[index];
if(cur==null)
return;
if (cur.getKey()==key){
a[index]=cur.getNext();
size--;
return;
}
Node parent=a[index];
cur=parent.getNext();
while(cur!=null){
if(cur.getKey()==key){
parent.setNext(cur.getNext());
size--;
return;
}
parent=cur;
cur=cur.getNext();
}
}
public void resize(){
Node[] temp=new Node[a.length*2];
for (int i = 0; i <a.length ; i++) {
Node cur=a[i];
while(cur!=null){
Node next=cur.getNext();
int index=cur.getKey()%temp.length;
cur.setNext(temp[index]);
temp[index]=cur;
cur=next;
}
}
a=temp;
}
}