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"));

	}

}



猜你喜欢

转载自wcl2184-163-com.iteye.com/blog/1453895