java哈希表实现_java实现哈希表

以下是我用java实现的哈希表

package com.husiwang.HashMap;

import com.husiwang.LinkList.LinkList;

/**

* Created by SiwangHu on 2015/2/5.

*/

public class HashMap {

private int Length;       //长度

private int Capacity;     //容量

private LinkList[] Key;    //键

private LinkList[] Value;  //值

private LinkList Keys;     //键

private Visit Visited;     //回调函数

private boolean[] Used;    //占位

public HashMap(){

Length=0;

Capacity=100;

Visited=new Visit();

Keys=new LinkList();

Key=new LinkList[Capacity];

Value=new LinkList[Capacity];

Used=new boolean[Capacity];

for (int i = 0; i 

Key[i]=new LinkList();

}

for (int i = 0; i 

Value[i]=new LinkList();

}

for(int i=0;i

Used[i]=false;

}

}

public HashMap(int capacity){

if(capacity>0) {

Length=0;

Capacity = capacity;

Visited=new Visit();

Keys=new LinkList();

Key = new LinkList[Capacity];

Value = new LinkList[Capacity];

Used=new boolean[Capacity];

for (int i = 0; i 

Key[i]=new LinkList();

}

for (int i = 0; i 

Value[i]=new LinkList();

}

for(int i=0;i

Used[i]=false;

}

}

else{

throw new RuntimeException("容量不能为空");

}

}

public  boolean IsEmpty(){

if(Length==0)

return true;

else

return false;

}

public int getLength() {

return Length;

}

public int getCapacity() {

return Capacity;

}

public LinkList getKeys() {

return Keys;

}

public int Hash(Object data){

return Math.abs(data.hashCode())%Capacity;

}

public void Put(Object key,Object value){

if(!HasKey(key)) {

int hash = Hash(key);

Used[hash]=true;

Keys.Insert(key);

Length++;

Key[hash].Insert(key);

Value[hash].Insert(value);

}

}

public Object Get(Object key){

if(HasKey(key)) {

int hash = Hash(key);

for (int i = 0; i 

if (Key[hash].Get(i) == key) {

return Value[hash].Get(i);

}

}

return null;

}

else{

throw new RuntimeException("无此关键字");

}

}

public void Remove(Object key){

if(HasKey(key)) {

int hash = Hash(key);

for (int i = 0; i 

if (Key[hash].Get(i) == key) {

Key[hash].Remove(i);

Value[hash].Remove(i);

Length--;

return;

}

}

}

}

public boolean HasKey(Object key){

return Keys.Find(key);

}

public void Traverse(){

Traverse(Visited);

}

public void Traverse(Visit visited){

for(int i=0;i

for(int j=0;j

if(Used[i]==true)

visited.visit(Key[i].Get(j),Value[i].Get(j));

}

}

}

}

package com.husiwang.HashMap;

import com.husiwang.LinkList.Node;

/**

* Created by SiwangHu on 2015/2/5.

*/

public class Visit {

public void visit(Object key,Object value){

System.out.println("Key="+key+" "+"value="+value);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值