java自写哈希表

hash表中的元素:




public class Item<K, V>
{
private K key;

private V value;

public Item(K key, V value)
{
this.key = key;
this.value = value;
}

public K getKey()
{
return key;
}

public void setKey(K key)
{
this.key = key;
}

public V getValue()
{
return value;
}

public void setValue(V value)
{
this.value = value;
}

@Override
public int hashCode()
{
return key.hashCode();
}

}



hash表实现:


public class HashTable<K, V>
{

private Item<K, V>[] items;
private int len;

public HashTable(int size)
{
this.items = new Item[size];
this.len = items.length;
}

public V put(K key, V value)
{
int hashAddr = key.hashCode() % len;
Item<K, V> item = new Item<K, V>(key, value);
if (items[hashAddr] == null)
{
items[hashAddr] = item;
return null;

} else
{
int i = 0;
for (; items[(hashAddr + i) % len] != null; i++)
{
// 取得当前元素
Item<K, V> curr = items[(hashAddr + i) % len];
// 替换
if (curr.getKey().equals(key))
{
V result = curr.getValue();
items[(hashAddr + i) % len] = item;
return result;
} else
{
// 已经走了一圈,退出
if ((hashAddr + i + 1) % items.length == hashAddr)
{
System.out.println("空间已满,【" + item.getKey() + "," + item.getValue() + "】 插入失败!");
return null;
}
}
}
items[(hashAddr + i) % items.length] = item;
return null;
}

}

public V get(K key)
{
int hashAddr = key.hashCode() % len;
for (int i = 0; items[(hashAddr + i) % items.length] != null; i++)
{
// 取得当前元素
Item<K, V> curr = items[(hashAddr + i) % len];

if (curr.getKey().equals(key))
{
return curr.getValue();
} else if ((hashAddr + i + 1) % items.length == hashAddr)
{
System.out.println("找了一圈未找到");
return null;
}
}
return null;
}

public V remove(K key)
{

int hashAddr = key.hashCode() % len;
for (int i = 0; items[(hashAddr + i) % items.length] != null; i++)
{
// 取得当前元素
Item<K, V> curr = items[(hashAddr + i) % len];
if (curr.getKey().equals(key))
{
items[(hashAddr + i) % len] = null;
return curr.getValue();
} else if ((hashAddr + i + 1) % items.length == hashAddr)
{
System.out.println("找了一圈未找到");
return null;
}
}
return null;

}

public static void main(String[] args)
{
HashTable<String, String> h = new HashTable<String, String>(5);

System.out.println(h.put("a", "测试a"));
System.out.println(h.put("a", "测试b"));
System.out.println(h.put("e", "测试e"));
System.out.println("-----------------------------");
System.out.println(h.remove("a"));
System.out.println(h.get("a"));
System.out.println(h.get("e"));

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值