`
baby69yy2000
  • 浏览: 182778 次
  • 性别: Icon_minigender_1
  • 来自: 自己输入城市...
社区版块
存档分类
最新评论

HashMap类的实现

    博客分类:
  • Util
J# 
阅读更多
package Hash;

import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;

import MyInterface.Iterator;
import MyInterface.Map;
import MyInterface.Set;

/**
 * HashMap的实现
 */
public class HashMap<K, V> implements Map<K, V> {

	// ----------------------------------------------------------------
	// 结点类
	private static class Entry<K, V> implements Map.Entry<K, V> {
		K key;
		V value;
		int hashValue;
		Entry<K, V> next;

		public Entry(K key, V value, int hashValue, Entry<K, V> next) {
			this.key = key;
			this.value = value;
			this.hashValue = hashValue;
			this.next = next;
		}

		public K getKey() {
			return key;
		}

		public V getValue() {
			return value;
		}

		public Entry<K, V> getNext() {
			return next;
		}

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

		public String toString() {
			return key + "=" + value;
		}

	}

	// ----------------------------------------------------------------

	private Entry[] table;
	private int hashMapSize;
	private final double MAX_LOAD_FACTOR = 0.75;
	private int tableThreshold;
	private int modCount = 0;

	// HashMap类构造函数
	public HashMap() {
		table = new Entry[17];
		hashMapSize = 0;
		tableThreshold = (int) (table.length * MAX_LOAD_FACTOR);
	}

	public V put(K key, V value) {
		int hashValue = key.hashCode() & Integer.MAX_VALUE, index = hashValue
				% table.length;
		Entry<K, V> entry;
		entry = table[index];
		while (entry != null) {
			if (entry.key.equals(key))
				return entry.setValue(value);
			entry = entry.next;
		}
		modCount++;
		entry = new Entry<K, V>(key, value, hashValue,
				(Entry<K, V>) table[index]);
		table[index] = entry;
		hashMapSize++;
		if (hashMapSize >= tableThreshold)
			rehash(2 * table.length + 1);
		return null;
	}

	private void rehash(int newTableSize) {
		Entry[] newTable = new Entry[newTableSize], oldTable = table;
		Entry<K, V> entry, nextEntry;
		int index, len = table.length;

		for (int i = 0; i < len; i++) {
			entry = table[i];
			if (entry != null) {
				table[i] = null;
				do {
					nextEntry = entry.next;
					index = entry.hashValue % newTableSize;
					entry.next = newTable[index];
					newTable[index] = entry;
					entry = nextEntry;
				} while (entry != null);
			}
		}
		table = newTable;
		tableThreshold = (int) (table.length * MAX_LOAD_FACTOR);
		oldTable = null;
	}

	public V get(Object key) {
		Entry<K, V> p = this.getEntry(key);
		if (p == null)
			return null;
		return p.value;
	}

	public Entry<K, V> getEntry(Object key) {
		int index = (key.hashCode() & Integer.MAX_VALUE) % table.length;
		Entry<K, V> entry;

		entry = table[index];

		while (entry != null) {
			if (entry.key.equals(key))
				return entry;
			entry = entry.next;
		}
		return null;
	}

	public void clear() {
		for (int i = 0; i < table.length; i++)
			table[i] = null;
		modCount++;
		hashMapSize = 0;
	}

	public boolean containsKey(Object key) {
		return getEntry(key) != null;
	}

	public boolean isEmpty() {
		return hashMapSize == 0;
	}

	public V remove(Object key) {
		int index = (key.hashCode() & Integer.MAX_VALUE) % table.length;
		Entry<K, V> curr, prev;

		curr = table[index];
		prev = null;
		while (curr != null) {
			if (curr.key.equals(key)) {
				modCount++;
				if (prev != null)
					prev.next = curr.next;
				else
					table[index] = curr.next;
				hashMapSize--;
				return curr.value;
			} else {
				prev = curr;
				curr = curr.next;
			}
		}
		return null;
	}

	public int size() {
		return hashMapSize;
	}

	public String toString() {
		int max = hashMapSize - 1;
	      StringBuffer buf = new StringBuffer();
	      Iterator<Map.Entry<K,V>> iter = entrySet().iterator();

	      buf.append("{");
	      for (int j = 0; j <= max; j++) {
	         Map.Entry<K,V> e = iter.next();
	         buf.append(e.getKey() + "=" + e.getValue());
	         if (j < max)
	            buf.append(", ");
	      }
	      buf.append("}");

	      return buf.toString();
	}
	
	// ----------------------------------------------------------------
	// 视图
	
	private Set<K> keySet = null;
	private Set<Map.Entry<K,V>> entrySet = null;
	
	public Set<K> keySet() {
		if(keySet == null) {
			keySet = new Set<K>() {

				public boolean add(K item) {
					throw new UnsupportedOperationException();
				}

				public void clear() {
					HashMap.this.clear();
				}

				public boolean contains(Object item) {
					return containsKey(item);
				}

				public boolean isEmpty() {
					return HashMap.this.size() == 0;
				}

				public Iterator<K> iterator() {
					return new KeyIterator();
				}

				public boolean remove(Object item) {
					int oldSize = size();
					HashMap.this.remove(item);
		            return size() != oldSize;
				}

				public int size() {
					return HashMap.this.size();
				}

				public Object[] toArray() {
					Object[] arr = new Object[size()];
					Iterator<K> iter = iterator();
					int len = arr.length;
					for (int i=0;i < len;i++)
						arr[i] = iter.next();
					return arr;
				}
				
				public String toString() {
					int max = size() - 1;
					StringBuffer buf = new StringBuffer();
					Iterator<K> iter = iterator();
					buf.append("[");
					while (iter.hasNext())
					{
						buf.append(iter.next());
						if (iter.hasNext())
							buf.append(", ");
					}
					buf.append("]");
					return buf.toString();
				}
				
			};
		}
		return keySet;
	}
	
	public Set<Map.Entry<K, V>> entrySet() {
		if(entrySet == null) {
			entrySet = new Set<Map.Entry<K, V>>() {

				public boolean add(Map.Entry<K, V> item) {
					throw new UnsupportedOperationException();
				}

				public void clear() {
					HashMap.this.clear();
				}

				public boolean contains(Object item) {
					if (!(item instanceof Map.Entry))
						return false;

					Entry<K,V> entry = (Entry<K,V>)item;
					V value = entry.value;
					Entry<K,V> p = getEntry(entry.key);

					return p != null && p.getValue().equals(value);
				}

				public boolean isEmpty() {
					return size() == 0;
				}

				public Iterator<Map.Entry<K, V>> iterator() {
					return new EntryIterator();
				}

				public boolean remove(Object item) {
					 Entry<K,V> entry = (Entry<K,V>)item;
		             K key = entry.key;
		             return HashMap.this.remove(key) != null;
				}

				public int size() {
					return HashMap.this.size();
				}

				public Object[] toArray() {
					Object[] arr = new Object[size()];
					Iterator<Map.Entry<K,V>> iter = iterator();
					int len = arr.length;
					for (int i=0;i < len;i++)
						arr[i] = iter.next();
					return arr;
				}
				
				public String toString() {
					return HashMap.this.toString();
				}
				
			};
		}
		return entrySet;
	}

	// ----------------------------------------------------------------
	// 跌代器
	private class IteratorImpl<T> implements Iterator<T> {
		Entry<K, V> next;
		int expectedModCount;
		int index;
		Entry<K, V> lastReturned;

		IteratorImpl() {
			int i = 0;
			Entry<K, V> n = null;
			expectedModCount = modCount;

			if (hashMapSize != 0)
				while (i < table.length && ((n = table[i]) == null))
					i++;
			next = n;
			index = i;
			lastReturned = null;
		}

		final Entry<K, V> nextEntry() {
			if (modCount != expectedModCount)
				throw new ConcurrentModificationException();

			Entry<K, V> entry = next;

			if (entry == null)
				throw new NoSuchElementException();
			lastReturned = entry;
			Entry<K, V> n = entry.next;
			int i = index;

			if (n == null) {
				// we are at the end of a bucket. search for the
				// next non-empty bucket
				i++;
				while (i < table.length && (n = table[i]) == null)
					i++;
			}

			index = i;
			next = n;

			return lastReturned;
		}

		public boolean hasNext() {
			return next != null;
		}

		public T next() {
			return null;
		}

		public void remove() {
			// check for a missing call to next() or previous()
			if (lastReturned == null)
				throw new IllegalStateException("Iterator call to next() "
						+ "required before calling remove()");
			if (modCount != expectedModCount)
				throw new ConcurrentModificationException();

			// remove lastReturned by calling remove() in Hash.
			// this call will increment modCount
			HashMap.this.remove(lastReturned.key);
			expectedModCount = modCount;
			lastReturned = null;
		}

	}

	private class KeyIterator extends IteratorImpl<K> {
		public K next() {
			return nextEntry().key;
		}
	}

	private class EntryIterator extends IteratorImpl<Map.Entry<K, V>> {
		public Map.Entry<K, V> next() {
			return nextEntry();
		}
	}

}


测试类
package Hash;

import MyInterface.Iterator;
import MyInterface.Set;
import MyInterface.Map;
import MyInterface.Map.Entry;

public class TestHashMap {

	public static void main(String[] args) {
		HashMap<String, Integer> hm = new HashMap<String, Integer>();
		hm.put("Agg", new Integer(50));
		hm.put("Bf", new Integer(60));
		hm.put("Cf", new Integer(10));
		System.out.println(hm); 	// {Cf=10, Agg=50, Bf=60}
		
		// test keySet
		Set<String> kS = hm.keySet();
		Iterator<String> iter = kS.iterator();
		while(iter.hasNext())
			System.out.println(iter.next());
		System.out.println(kS);
		
		// test entrySet
		Set<Map.Entry<String, Integer>> eS = hm.entrySet();
		Iterator<Entry<String, Integer>> it = eS.iterator();
		Entry<String, Integer> e = null;
		while(it.hasNext()) {
			e = it.next();
			System.out.println(e.getValue() + "=" + e.getKey());
		}
		System.out.println(eS);
		
		// test remove
		hm.remove("Bf");
		System.out.println(hm); // {Cf=10, Agg=50}
		
		System.out.println(hm.size()); // 2
		System.out.println(hm.containsKey("Bf")); // false
		hm.clear();
		System.out.println(hm.isEmpty()); // true
	}

}
分享到:
评论

相关推荐

    HashMap重写实现

    HashMap重写实现 轻量级实现 使用自定义的轻量对象HashObjectMap替代jdk的HahMap HashMap里的Entry占用较大内存,可以用自己实现的轻量级容器替换,步骤如下: 1、 缓存的对象需要继承BaseHashObject /** * 这个类...

    自定义map实现java的hashmap

    用数据结构的思想实现java中的类hashmap

    HashMap类

    NULL 博文链接:https://wenkaixuan.iteye.com/blog/1075214

    枚举 HashMap

    用HashMap实现的仿枚举功能类 有兴趣的朋友可以看看

    Java中HashMap详解(通俗易懂).doc

    HashMap和HashSet是Java Collection Framework的两个重要成员,其中HashMap是Map接口的常用实现类,HashSet是Set接口的常用实现类。虽然HashMap和HashSet实现的接口规范不同,但它们底层的Hash存储机制完全一样,...

    HashMap模块源码—— 高效随机存取数据结构 ,文本索引必备

    1、此HashMap类采用java jdk中HashMap的实现方式。2、相比网站上发布过的hashtable之类的源码:。此HashMap寻址方法是拉链法.比开放寻址法对连续内存要求更低。哈希函数用的是java中String.hashCode()算法(经实际验证...

    一个基于js的HashMap

    一个用于js里面 用javascript实现的HashMap类

    HashMap-面试必过

    1.说一下 HashMap 的实现原理? 2.HashMap在JDK1.7和JDK1.8中有哪些不同?HashMap的底层实现? 3.HashMap的put方法的具体流程? 4.HashMap的扩容操作是怎么实现的? 5.HashMap是怎么解决哈希冲突的? 6.什么是哈希?...

    java中HashMap详解

    因此,在使用HashMap时需要进行同步处理或者使用线程安全的HashMap实现类。 动态扩容:当HashMap中的元素数量超过了容量(默认为16)与负载因子(默认为0.75)的乘积时,HashMap会自动扩容,即创建一个新的数组,并将...

    易语言-HashMap模块源码—— 高效随机存取数据结构 ,文本索引必备

    1、此HashMap类采用java jdk中HashMap的实现方式 2、相比网站上发布过的hashtable之类的源码: 此HashMap寻址方法是拉链法.比开放寻址法对连续内存要求更低 哈希函数用的是java中String.hashCode()算法(经实际验证其...

    javascript实现的HashMap类代码

    主要介绍了javascript实现的HashMap类代码,实现了添加、获取、删除、查询key和value功能,需要的朋友可以参考下

    容器之ArrayList与HashMap底层实现

    1. 测试ArrayList类的方法: package RongQI.Collection; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * 测试Collection接口中的方法 */ public class TestArraylist {...

    js 集合类实现 (HashMap, Set, ArrayList, etc.)

    javascript collections (HashMap, Set, ArrayList, etc.)

    Hashtable和HashMap的区别:

    1.Hashtable是Dictionary的子类,HashMap是Map接口的一个实现类; 2.Hashtable中的方法是同步的,而HashMap中的方法在缺省情况下是非同步的。即是说,在多线程应用程序中,不用专门的操作就安全地可以使用Hashtable...

    java-hashmap:Java HashMap的插图

    HashMap类使用哈希表来实现Map接口。 这样,即使对于大型集合,诸如get()和put()之类的基本操作的执行时间也可以保持恒定。 目录 插图1:使用put()方法在HashMap中创建和添加对象 插图2:使用size()方法...

    易语言HashMap类源码-易语言

    易语言HashMap类源码

    c语言实现哈希字典Hashmap

    做项目写业务逻辑的时候经常用到的数据...但是c语言是没有提供这类标准库的,本资源提供的是一个可以在正式项目中使用的纯c语言实现的哈希字典。原文链接:https://blog.csdn.net/u013113678/article/details/113765937

    ASP实现类似hashMap功能的类

    主要介绍了ASP实现类似hashMap功能的类

Global site tag (gtag.js) - Google Analytics