使用JAVA实现散列的数据结构

一、散列

散列是为了解决快速插入和快速查找的功能,它是基于数组+链表来实现的

1.散列结构

散列结构

  • 散列的节点:实际存储的节点
  • 散列函数:hash函数,它通过一定的算法将所存储节点的key转化为一个整数,我们可以根据这个计算出来的整数值来确定它应该存储到散列表的什么位置
  • 散列表:用于存放一系列散列节点的表

注:我们通过key计算出其hashCode值,但不同的key可能其hashCode值相同,这就是所谓的hash碰撞,处理hash碰撞就很多方式,比如重新hash,还有开放地址法等,我们这里采用链表的方式来处理哈希碰撞

2.利用链表来解决hash冲突
  • 如果计算出的hash值,与原来的某个节点相同,而它应该存储的位置被另外一个节点占用了,此时,我们可以在存储位置的节点加上一个next指针,指向新的加入到这个位置的节点

二、动手实现一个散列结构

1.散列表的几个组成部分
  • size : 散列表元素个数 
  • nodes : 存储节点的数组
  • capacity:占用的空间
  • Node : 节点定义
  1. /**
  2. * 散列表的大小
  3. */
  4. private int size;
  5. /**
  6. * 散列表存储节点的数组
  7. */
  8. private Node<K, V>[] nodes;
  9. /**
  10. * 容量
  11. */
  12. private int capacity;
  13. /*
  14. * 散列表的节点
  15. */
  16. private class Node<K, V> {
  17.   //键
  18. private K key;
  19. //值
  20. private V value;
  21. //键对应的hash码
  22. private int hashCode;
  23. //键的下一个节点指针
  24. private Node<K, V> next;
  25. }
2.添加元素(包括重置元素值)
  • 新增的元素:该键不存在,查找到元素应该存储的位置,如果所有位置已经被占用,则在应该存储的位置的第后一个节点,通过next指针指向新增的节点
  • 修改元素的值:该键已经存在,查找到元素修改值即可
  1. /**
  2. * 添加元素
  3. * @param key
  4. * @param value
  5. * @return
  6. */
  7. public boolean put(K key, V value) {
  8. //1.新添加一个节点
  9. Node<K, V> node = new Node<K, V>(key, value, null);
  10. //2.计算出节点存储到数组中的位置
  11. int index = getIndex(node.getHashCode());
  12. //3.查找存储的位置上的节点
  13. Node<K, V> indexNode = (Node<K, V>) nodes[index];
  14. //4.定义一个是否为新节点的标识(默认为新增节点)
  15. boolean newNode = true;
  16. //5.如果插入的位置上节点不存在,那么直接将新增节点放入这个位置即可
  17. if (indexNode == null) {
  18. nodes[index] = node;
  19. } else {
  20.    //否则说明该位置上有其他节点,定义一个当前指针 
  21. Node<K, V> current = indexNode;
  22. //6.如果当前节点的下一个节点不为null,即这个位置有不少于2个节点的数据,一直遍历
  23. while (current.getNext() != null) {
  24.    //7.如果插入的键已经存在 
  25. if (key.equals(current.getKey())) {
  26. //插入的值存在的话,那么修改它的值,并且将newNode设置为false,即不是新增节点
  27. current.setValue(value);
  28. newNode = false;
  29. break;
  30. }
  31. current = current.getNext();
  32. }
  33. //8.如果是新增节点,设置最后一个节点的next为新增的节点
  34. if (newNode) {
  35. current.setNext(node);
  36. }
  37. }
  38. //9.如果是新增节点,则更新表节点的长度
  39. if (newNode) {
  40. this.size ++;
  41. }
  42. return true;
  43. }
3.获取元素
  • 先通过key计算出节点在数组中的存储位置
  • 再在相应的位置上查找与key相等的节点即可
  1. /**
  2. * 获取元素值
  3. * @param k
  4. * @return
  5. */
  6. public V get(K k) {
  7. //1.获取键对应的索引位置
  8. int index = getIndex(k.hashCode());
  9. //2.获取该位置的节点
  10. Node<K, V> node = nodes[index];
  11. if (node != null) {
  12. Node<K, V> current = node;
  13. //遍历包含节点在内的链表,一直查找到与key相等的节点
  14. while (current != null) {
  15. if (k.equals(current.getKey())) {
  16. return current.getValue();
  17. }
  18. current = current.getNext();
  19. }
  20. }
  21. return null;
  22. }
4.删除元素值
  • 先通过key找到存储节点的位置
  • 依次遍历位置上所有的节点,并记录遍历的节点的前一个节点,如果当前节点的key与删除的key相等
    • 那么首先获取删除元素的值
    • 如果删除元素的前一个元素为null,即删除的存储位置的第一个元素,那么让存储位置的元素指向当前删除元素的下一个元素
    • 如果删除元素不是第一个元素,那么将删除元素的上一个元素的next指针指向删除元素的下一个元素
    • 删除当前元素存储的值
  1. /**
  2. * 删除某个key对应的元素
  3. * @param key
  4. * @return
  5. */
  6. public V remove(K key) {
  7. //1.通过key获取在数组中的存储位置
  8. int index = getIndex(key.hashCode());
  9. //2.通过位置获取节点
  10. Node<K, V> current = nodes[index];
  11. //3.如果不存在,直接返回
  12. if (current == null) {
  13. return null;
  14. }
  15. //4.定义删除节点的前一个节点
  16. Node<K, V> prev = null;
  17. while (current != null) {
  18. //5.如果查找到key对应的节点
  19. if (current.getKey().equals(key)) {
  20. //获取原值
  21. V oldValue = current.getValue();
  22. //如果上一个节点不为null,即删除的节点不是所在位置的第一个元素
  23. if (prev != null) {
  24. //设置前一个节点的next指向删除元素的下一个元素
  25. prev.setNext(current.getNext());
  26. } else {
  27. //将数组对应的位置设置为当前元素的上一个元素(因为第一个元素已经被删除了,所以要更新数组中的对应的元素)
  28. nodes[index] = current.getNext();
  29. }
  30. //清除删除元素
  31. current = null;
  32. //节点数更新
  33. size --;
  34. return oldValue;
  35. }
  36. //6.记录上一个节点
  37. prev = current;
  38. //7.当前节点下移
  39. current = current.getNext();
  40. }
  41. return null;
  42. }
5.散列的实现完整代码
  1. package com.shixinke.demo.dataStruct;
  2. public class MyHashMap<K,V> {
  3. /**
  4. * 散列表的大小
  5. */
  6. private int size;
  7. /**
  8. * 散列表存储节点的数组
  9. */
  10. private Node<K, V>[] nodes;
  11. /**
  12. * 容量
  13. */
  14. private int capacity;
  15. /**
  16. * 默认的容量
  17. */
  18. private static final int DEFAULT_CAPACITY = 5;
  19. /**
  20. * 不带参数的初始化,使用默认容量
  21. */
  22. public MyHashMap() {
  23. this.capacity = DEFAULT_CAPACITY;
  24. clearMap();
  25. }
  26. /**
  27. * 指定容量初始化
  28. * @param capacity
  29. */
  30. public MyHashMap(int capacity) {
  31. if (capacity > DEFAULT_CAPACITY) {
  32. this.capacity = capacity;
  33. } else {
  34. this.capacity = DEFAULT_CAPACITY;
  35. }
  36. clearMap();
  37. }
  38. /**
  39. * 清除占用的空间
  40. */
  41. public void clear() {
  42. clearMap();
  43. }
  44. public void clearMap() {
  45. this.size = 0;
  46. this.nodes = new Node[this.capacity];
  47. }
  48. /**
  49. * 添加元素
  50. * @param key
  51. * @param value
  52. * @return
  53. */
  54. public boolean add(K key, V value) {
  55. return put(key, value);
  56. }
  57. /**
  58. * 添加元素
  59. * @param key
  60. * @param value
  61. * @return
  62. */
  63. public boolean put(K key, V value) {
  64. //1.新添加一个节点
  65. Node<K, V> node = new Node<K, V>(key, value, null);
  66. //2.计算出节点存储到数组中的位置
  67. int index = getIndex(node.getHashCode());
  68. //3.查找存储的位置上的节点
  69. Node<K, V> indexNode = (Node<K, V>) nodes[index];
  70. //4.定义一个是否为新节点的标识(默认为新增节点)
  71. boolean newNode = true;
  72. //5.如果插入的位置上节点不存在,那么直接将新增节点放入这个位置即可
  73. if (indexNode == null) {
  74. nodes[index] = node;
  75. } else {
  76. //否则说明该位置上有其他节点,定义一个当前指针 
  77. Node<K, V> current = indexNode;
  78. //6.如果当前节点的下一个节点不为null,即这个位置有不少于2个节点的数据,一直遍历
  79. while (current.getNext() != null) {
  80. //7.如果插入的键已经存在 
  81. if (key.equals(current.getKey())) {
  82. //插入的值存在的话,那么修改它的值,并且将newNode设置为false,即不是新增节点
  83. current.setValue(value);
  84. newNode = false;
  85. break;
  86. }
  87. current = current.getNext();
  88. }
  89. //8.如果是新增节点,设置最后一个节点的next为新增的节点
  90. if (newNode) {
  91. current.setNext(node);
  92. }
  93. }
  94. //9.如果是新增节点,则更新表节点的长度
  95. if (newNode) {
  96. this.size ++;
  97. }
  98. return true;
  99. }
  100. /**
  101. * 获取元素值
  102. * @param k
  103. * @return
  104. */
  105. public V get(K k) {
  106. //1.获取键对应的索引位置
  107. int index = getIndex(k.hashCode());
  108. //2.获取该位置的节点
  109. Node<K, V> node = nodes[index];
  110. if (node != null) {
  111. Node<K, V> current = node;
  112. //遍历包含节点在内的链表,一直查找到与key相等的节点
  113. while (current != null) {
  114. if (k.equals(current.getKey())) {
  115. return current.getValue();
  116. }
  117. current = current.getNext();
  118. }
  119. }
  120. return null;
  121. }
  122. /**
  123. * 删除某个key对应的元素
  124. * @param key
  125. * @return
  126. */
  127. public V remove(K key) {
  128. //1.通过key获取在数组中的存储位置
  129. int index = getIndex(key.hashCode());
  130. //2.通过位置获取节点
  131. Node<K, V> current = nodes[index];
  132. //3.如果不存在,直接返回
  133. if (current == null) {
  134. return null;
  135. }
  136. //4.定义删除节点的前一个节点
  137. Node<K, V> prev = null;
  138. while (current != null) {
  139. //5.如果查找到key对应的节点
  140. if (current.getKey().equals(key)) {
  141. //获取原值
  142. V oldValue = current.getValue();
  143. //如果上一个节点不为null,即删除的节点不是所在位置的第一个元素
  144. if (prev != null) {
  145. //设置前一个节点的next指向删除元素的下一个元素
  146. prev.setNext(current.getNext());
  147. } else {
  148. //将数组对应的位置设置为当前元素的上一个元素(因为第一个元素已经被删除了,所以要更新数组中的对应的元素)
  149. nodes[index] = current.getNext();
  150. }
  151. //清除删除元素
  152. current = null;
  153. //节点数更新
  154. size --;
  155. return oldValue;
  156. }
  157. //6.记录上一个节点
  158. prev = current;
  159. //7.当前节点下移
  160. current = current.getNext();
  161. }
  162. return null;
  163. }
  164. /**
  165. * 获取表的长度
  166. * @return
  167. */
  168. public int size() {
  169. return size;
  170. }
  171. /**
  172. * 是否为空
  173. * @return
  174. */
  175. public boolean isEmpty() {
  176. return size() == 0;
  177. }
  178. /**
  179. * 是否包含某个key
  180. * @param key
  181. * @return
  182. */
  183. public boolean containsKey(K key) {
  184. //1.通过键获取键存储的位置 
  185. int index = getIndex(key.hashCode());
  186. //2.通过索引查找到在数组中的节点
  187. Node<K, V> current = nodes[index];
  188. //3.如果位置上的节点为null,即不存在,直接返回
  189. if (current == null) {
  190. return false;
  191. }
  192. //4.遍历比较key与链表中的key是否一致
  193. while (current != null) {
  194. if (current.getKey().equals(key)) {
  195. return true;
  196. }
  197. current = current.getNext();
  198. }
  199. return false;
  200. }
  201. /**
  202. * 打印散列表数据
  203. */
  204. public void print() {
  205. Node<K, V> p = null;
  206. System.out.print("{");
  207. for (int i = 0; i < nodes.length; i++) {
  208. p = nodes[i];
  209. while ( p != null) {
  210. System.out.print("["+i+"]:"+p.getKey()+"="+p.getValue()+",");
  211. p = p.getNext();
  212. }
  213. }
  214. System.out.println("}");
  215. }
  216. /**
  217. * 获取某个值在数组中的对应的索引
  218. * @param hashCode
  219. * @return
  220. */
  221. private int getIndex(int hashCode) {
  222. return hashCode % this.capacity;
  223. }
  224. /**
  225. * 散列表节点
  226. * @param <K>
  227. * @param <V>
  228. */
  229. private class Node<K, V> {
  230. //键
  231. private K key;
  232. //值
  233. private V value;
  234. //键对应的hash码
  235. private int hashCode;
  236. //当前键的下一个节点
  237. private Node<K, V> next;
  238. public Node(K key, V value, Node<K, V> next) {
  239. this.key = key;
  240. this.value = value;
  241. this.hashCode = key.hashCode();
  242. this.next = next;
  243. }
  244. public K getKey() {
  245. return key;
  246. }
  247. public V getValue() {
  248. return value;
  249. }
  250. public int getHashCode() {
  251. return hashCode;
  252. }
  253. public void setValue(V value) {
  254. this.value = value;
  255. }
  256. public void setNext(Node<K, V> next) {
  257. this.next = next;
  258. }
  259. public Node<K, V> getNext() {
  260. return next;
  261. }
  262. }
  263. }
6.例子
  1. MyHashMap<String, Integer> testMap = new MyHashMap<>(3);
  2. testMap.put("A", 1);
  3. testMap.put("B", 2);
  4. testMap.put("C", 3);
  5. testMap.put("D", 4);
  6. testMap.put("E", 5);
  7. testMap.put("F", 6);
  8. testMap.put("G", 7);
  9. testMap.print(); //{[0]:A=1,[0]:F=6,[1]:B=2,[1]:G=7,[2]:C=3,[3]:D=4,[4]:E=5,}
  10. System.out.println(testMap.containsKey("F")); //true
  11. System.out.println(testMap.get("F")); //6
  12. testMap.remove("F");
  13. testMap.print(); //{[0]:A=1,[1]:B=2,[1]:G=7,[2]:C=3,[3]:D=4,[4]:E=5,}
  14. testMap.remove("E");
  15. testMap.print(); //{[0]:A=1,[1]:B=2,[1]:G=7,[2]:C=3,[3]:D=4,}