java实现一个简单的哈希表
package hash ;
public class HashMap {
static class Node {
public int key;
public int value;
public Node next;
public Node ( int key, int value) {
this . key = key;
this . value = value;
}
}
private Node [ ] quick_find;
private int capacity;
private static final double balance = 0.75 ;
private int size;
public HashMap ( ) {
capacity = 101 ;
quick_find = new Node [ capacity] ;
size = 0 ;
}
public void expand ( ) {
if ( size/ capacity < balance) {
return ;
}
Node [ ] increase = new Node [ capacity* 2 ] ;
capacity = 2 * capacity;
for ( int i = 0 ; i < capacity/ 2 ; i++ ) {
Node head = quick_find[ i] ;
if ( head != null ) {
int index = head. key% capacity;
increase[ index] = head;
}
}
quick_find = increase;
return ;
}
public void put ( int key, int value) {
expand ( ) ;
int index = key% capacity;
Node head = quick_find[ index] ;
while ( head != null ) {
if ( head. key == key ) {
head. value = value;
return ;
}
head = head. next;
}
Node node = new Node ( key, value) ;
head = quick_find[ index] ;
node. next = head;
quick_find[ index] = node;
size++ ;
}
public Integer get ( int key) {
int index = key% capacity;
Node head = quick_find[ index] ;
while ( head != null ) {
if ( head. key == key) return head. value;
head = head. next;
}
return null ;
}
public void remove ( int key) {
int index = key% capacity;
Node head = quick_find[ index] ;
if ( head == null || get ( key) == null ) return ;
head = delete ( head, key) ;
quick_find[ index] = head;
size-- ;
}
private Node delete ( Node head, int key) {
Node cur = head;
Node prev = null ;
while ( cur != null ) {
if ( cur. key == key) {
if ( prev == null ) {
return head. next;
} else {
prev. next = cur. next;
}
prev = cur;
cur = cur. next;
}
}
return head;
}
public static void main ( String [ ] args) {
HashMap map = new HashMap ( ) ;
map. put ( 1 , 2 ) ;
map. put ( 1 , 3 ) ;
map. put ( 1 , 4 ) ;
map. put ( 102 , 3 ) ;
map. put ( 2 , 5 ) ;
map. put ( 3 , 9 ) ;
map. remove ( 2 ) ;
}
}