Map接口
package com.xununan.www.map; /** * @packageName com.xununan.www.map * @className Map * @description: 自定义Map * @author: xu * @create: 2020/04/26 22:25 */ public interface Map<K, V> { public V put(K k, V v); public V get(K k); public int size(); public interface Entry<K, V> { public K getKey(); public V getValue(); } }Map实现:数组 + 链表的方式
package com.xununan.www.map; /** * @packageName com.xununan.www.map * @className MyMap * @description: 自定义Map类 * @author: xu * @create: 2020/04/26 22:27 */ public class MyMap<K, V> implements Map<K, V> { private Entry[] table = null; private int size = 0; public MyMap() { table = new Entry[16]; } /** * 功能描述:put <br> * 1. key查询hashCode * 2. hashCode取模获得下标 * 3. 根据下标找到数组对象 * 4. 是否为空进行存储 * @param k * @param v * @return V * * @Author xu * @Date 2020-04-26 22:32 * @Version 1.0.0 */ @Override public V put(K k, V v) { int index = this.hash(k); Entry<K, V> entry = table[index]; if (entry == null) { table[index] = new Entry(k, v, k.hashCode(), null); size ++ ; } else { table[index] = new Entry(k, v, k.hashCode(), entry); } return (V) table[index].getValue(); } private int hash(K k) { return Math.abs(k == null ? 0 : k.hashCode() % 16); } /** * 功能描述:get <br> * 1. key找到index * 2. 数组位置 * 3. 判断当前对象是否有值,有的话比较对象的hashcode * 4. 如果当前hashcode值详单则直接返回如果不相等则继续比较下一个对象的hashcode * @param k * @return V * * @Author xu * @Date 2020-04-26 22:43 * @Version 1.0.0 */ @Override public V get(K k) { int index = this.hash(k); Entry<K,V> entry = table[index]; if (entry == null) { return null; } do { if (k.hashCode() == entry.hashCode) { return entry.getValue(); } else { entry = entry.next; } } while (entry != null); return null; // return this.find(index, entry); } private V find(int index, Entry<K,V> entry) { if (entry.hashCode == index) { return entry.getValue(); } else { if (entry.next != null) { return find(index, entry.next); } else { return null; } } } @Override public int size() { return size; } class Entry<K, V> implements Map.Entry<K, V> { K k; V v; int hashCode; Entry<K, V> next; public Entry(K k, V v, int hashCode, Entry<K, V> next) { this.k = k; this.v = v; this.hashCode = hashCode; this.next = next; } @Override public K getKey() { return k; } @Override public V getValue() { return v; } } }以上为个人总结的一些笔记,若有雷同纯属巧合,若有错误欢迎指出,谢谢!