散列表,也叫哈希表,是根据关键码和值 (key和value) 直接进行访问的数据结构,通过key和value来映射到集合中的一个位置,这样就可以很快找到集合中的对应元素
    哈希表 - 图1

    1. /**
    2. * 哈希表
    3. */
    4. public class HashTable {
    5. /**
    6. * 链表数组
    7. */
    8. private LinkedList[] linkedList;
    9. /**
    10. * 默认大小
    11. */
    12. private int size = 10;
    13. public HashTable() {
    14. this.linkedList = new LinkedList[size];
    15. for(int i = 0; i< this.linkedList.length; i++) {
    16. this.linkedList[i] = new LinkedList();
    17. }
    18. }
    19. /**
    20. * 哈希函数
    21. * @return
    22. */
    23. private int getHash(Integer id) {
    24. return id % 10;
    25. }
    26. /**
    27. * 添加元素
    28. * @param node
    29. */
    30. public void add(Node node) {
    31. // 获取对应的索引
    32. int hash = getHash(node.getId());
    33. linkedList[hash].add(node);
    34. }
    35. /**
    36. * 获取元素
    37. */
    38. public Node get(Integer id) {
    39. // 获取对应的索引
    40. int hash = getHash(id);
    41. return linkedList[hash].get(id);
    42. }
    43. /**
    44. * 打印所有元素
    45. */
    46. public void list() {
    47. for(int i = 0; i< this.linkedList.length; i++) {
    48. System.out.println("第" + i + "号链表");
    49. this.linkedList[i].list();
    50. }
    51. }
    52. public static void main(String[] args) {
    53. HashTable hashTable = new HashTable();
    54. Scanner scanner = new Scanner(System.in);
    55. boolean loop = true;
    56. while (loop) {
    57. System.out.print("【哈希表】添加(1)、查找(2)、打印(3)、退出(0):");
    58. Integer key = scanner.nextInt();
    59. switch (key) {
    60. case 1:
    61. System.out.print("Id:");
    62. int id = scanner.nextInt();
    63. System.out.print("Name:");
    64. String name = scanner.next();
    65. Node node = new Node(id, name);
    66. hashTable.add(node);
    67. break;
    68. case 2:
    69. System.out.print("查找的Id:");
    70. int id2 = scanner.nextInt();
    71. Node node2 = hashTable.get(id2);
    72. System.out.println(node2);
    73. break;
    74. case 3: hashTable.list(); break;
    75. case 0:
    76. scanner.close();
    77. loop = false;
    78. break;
    79. default: break;
    80. }
    81. }
    82. System.out.println("程序退出。。。");
    83. }
    84. }