HashMap原理介绍

5、HashMap

hashmap的put方法;

hashmap的get方法;

hashmap的扩容机制(初始容量-16、负载因子-0.75、扩容数量);

初始容量 > 16 * 0.75时,开始扩容

手动编写一个hashmap;

6、jdk1.8对hashmap的优化:

7、demo源码:

public interface DNMap<K, V> {
	/**
	 * put方法
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	V put(K key, V value);

	/**
	 * get方法
	 * 
	 * @param key
	 * @return
	 */
	V get(K key);

	/**
	 * 获取大小
	 * 
	 * @return
	 */
	int size();

	/**
	 * 内部接口
	 * 
	 * @param <K>
	 * @param <V>
	 */
	interface Entry<K, V> {
		K getKey();

		V getValue();
	}
}

/**
 * 实现类
 * 
 * @param <K>
 * @param <V>
 */
public class DNHashMap<K, V> implements DNMap<K, V> {

	private static Integer defaultLength = 16; // 初始容量

	private static double defaultLoad = 0.75; // 负载因子

	private Entry<K, V>[] table = null; // 数组,里面存的是<key、value和Entry>

	private int size = 0; // 记录数组的元素个数

	/**
	 * put方法
	 */
	@Override
	public V put(K key, V value) {
		// 1、根据key 和hash函数取到数组中的下标
		int index = this.getIndex(key);

		// 2、根据这个下标判定该位置是否有数据
		Entry<K, V> e = table[index];
		if (null == e) {
			table[index] = new Entry(key, value, null, index);
			size++;
		} else {
			Entry newEntry = new Entry(key, value, e, index);
			table[index] = newEntry;
		}
		return table[index].getValue();
	}

	/**
	 * get方法
	 */
	@Override
	public V get(K key) {
		// 1、根据key 和hash函数取到数组中的下标
		int index = this.getIndex(key);
		// table[index].getValue() 需要进行空判定
		return table[index] == null ? null : table[index].getValue();
	}

	/**
	 * 获取大小
	 */
	@Override
	public int size() {
		return size;
	}

	private int getIndex(K key) {
		// 取模(除留取余数)
		int m = this.defaultLength - 1;
		return key.hashCode() % m;
	}

	/**
	 * 构建函数
	 */
	DNHashMap(int defaultLength, double defaultLoad) {
		this.defaultLength = defaultLength;
		this.defaultLoad = defaultLoad;
		table = new Entry[defaultLength];
	}

	DNHashMap() {
		this(defaultLength, defaultLoad);
	}

	/**
	 * 内部类每一个entry对象里面有3个值(key value entry对象-指向下一个元素)
	 * 
	 * @param <K>
	 * @param <V>
	 */
	class Entry<K, V> implements DNMap.Entry<K, V> {

		K key;

		V value;

		Entry<K, V> next; // 指向下一个元素

		int index; // 记录entry在数组中的位置

		Entry(K k, V v, Entry<K, V> n, int inx) {
			key = k;
			value = v;
			next = n;
			index = inx;
		}

		@Override
		public K getKey() {
			return key;
		}

		@Override
		public V getValue() {
			return value;
		}
	}
}
public class Test {
	public static void main(String[] args) {
		DNHashMap<String, Object> map = new DNHashMap<String, Object>();
		map.put("name", "张三");
		map.put("age", 22);
		System.out.println("姓名是:" + map.get("name"));
		System.out.println("年龄是:" + map.get("age"));
	}
}

猜你喜欢

转载自blog.csdn.net/z_alvin/article/details/82078230