这一篇是基于线性探测的散列表

//总感觉性能不如拉链法的散列表,java自带的那个实现也是用的拉链法

//测试类如下:

public class Fucktest{
    public static void main(String[] args) {
        tanceSanLieBiao sanlie=new tanceSanLieBiao();

        int num=1;
        char i = 'a';
        for (; i <'z'+1; i++,num++) {
            sanlie.put(String.valueOf(i),num);

        }

        i='a';
        for(int tmp=1;tmp<27;tmp++){

            System.out.println(sanlie.get(String.valueOf(i++)));
        }
        
    }
}



//实现类如下:

/**
 * Created by eminem on 16-11-23.
 */

//基于线性探测法散列表

public class tanceSanLieBiao {

    //散列表(数组)长度
    private int M=16;
    //键值对数量
    private int N;

    private String[] keys;
    private Integer[] valuse;

    public tanceSanLieBiao(){
        keys=(String[]) new Object[M];
        valuse=(Integer[]) new Object[M];
    }

    public tanceSanLieBiao(int N){
        keys=(String[]) new Object[N];
        valuse=(Integer[]) new Object[N];
        M=N;
    }

    private int hash(String key){
        return (key.hashCode()&0x7fffffff)%M;
    }

    private void resize(int cap){
        tanceSanLieBiao tance=new tanceSanLieBiao(cap);

        for (int i=0;iM/2) resize(M*2);

        int i;
        for(i=hash(key);keys[i]!=null;i=(i++%M)){
            if(keys[i].equals(key)){
                valuse[i]=value;
                return;
            }
        }
        keys[i]=key;
        valuse[i]=value;

        N++;
    }

    public Integer get(String key){
        for(int i=hash(key);keys[i]!=null;i=(i++%M)){
            if(keys[i].equals(key)){
                return valuse[i];
            }
        }
        return null;
        
    }

}


//没实现删除操作









你可能感兴趣的:(算法4答案)