`
xglv2013
  • 浏览: 37235 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HashMap java实现

    博客分类:
  • Java
阅读更多
1.hashMap类
package hashMap;

import java.util.LinkedList;

public class LvHashMap<K,V> {
	LinkedList[] buckets;//桶数组, 元素类型是链表
	int bucketCount;
	LvHashMap(int bucketCount)
	{
		this.bucketCount = bucketCount;
		buckets = new LinkedList[bucketCount];
		for(int i = 0; i <= bucketCount - 1; i++)
		{
			LinkedList<Pair> l = new LinkedList<Pair>();
			buckets[i] = l;
		}
	}
	
	public void put(K key, V value)
	{
		int hashCode = key.hashCode();
		int index = hashCode % bucketCount;
		for(int i = 0; i <= buckets[index].size() - 1; i++)
		{
			if(((Pair) buckets[index].get(i)).getKey() == key)
			{
				((Pair) buckets[index].get(i)).setValue(value);
				return;
			}
		}
		buckets[index].add(new Pair(key, value));
	}
	
	public V get(K key)
	{
		int hashCode = key.hashCode();
		int index = hashCode % bucketCount;
		for(int i = 0; i <= buckets[index].size() - 1; i++)
		{
			if(((Pair) buckets[index].get(i)).getKey() == key)
			{
				return (V) ((Pair) buckets[index].get(i)).getValue();
			}
		}
		return null;
	}
}

2.链表节点实体类:
package hashMap;

public class Pair {
	Object key;
	Object value;
	Pair(Object key, Object value)
	{
		this.key = key;
		this.value = value;
	}
	public Object getKey() {
		return key;
	}
	public Object getValue() {
		return value;
	}
	public void setValue(Object value) {
		this.value = value;
	}
}

3.测试类:
package hashMap;

public class HashTestDemo 
{
	public static void main(String[] args){
		LvHashMap<String, String> hashMap = new LvHashMap<String, String>(32);
		hashMap.put("key", "value");
		hashMap.put("key", "value2");
		System.out.println(hashMap.get("key"));
		
        LvHashMap<String, Object> hashMap2 = new LvHashMap<String, Object>(32);
        int[] array1 = {1, 2, 3, 4, 5, 6};
        hashMap2.put("key", array1);
        System.out.println(hashMap2.get("key") == array1);
	}
}
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics