HashTable:遇到碰撞

Vri*_*ngh 0 java collections hashtable

   Hashtable ht = new Hashtable();
    for (int i = 0; i < 100; i++) {
        ht.put(i%10, i);
    }

    Enumeration< Integer> eles = ht.elements();
    while(eles.hasMoreElements())
        System.out.println(eles.nextElement());
Run Code Online (Sandbox Code Playgroud)

上面的代码片段是打印99,98,....... 90

但我想要打印所有100个元素.如何获得一个数字列表,如... 99,89,79,69,... 19,9 98,88,78,68 .... 18,8 97,87,77,67 .... 17,7 .. .. 91,81,71,61 .... 11,1

基本上都是碰撞清单.

Dun*_*nes 6

您当前正在使用i % 10哈希映射键,它只有十个值(0-9).因此,只有最后十个值存储在地图中,所有其他值都被覆盖.

如果您需要在每个存储桶中存储多个项目,请使用列表类型作为您的值.例如:

Hashtable<Integer, List<Integer>> ht = new Hashtable<>();
for (int i = 0; i < 100; i++) {
  int key = i % 10;
  List<Integer> list = ht.get(key);
  if (list == null) {
    list = new ArrayList<>();
    ht.put(key, list);
  }
  list.add(i);      
}

Enumeration<List<Integer>> eles = ht.elements();
while (eles.hasMoreElements()) {
  System.out.println(Arrays.toString(eles.nextElement().toArray()));
}
Run Code Online (Sandbox Code Playgroud)

输出:

[9, 19, 29, 39, 49, 59, 69, 79, 89, 99]
[8, 18, 28, 38, 48, 58, 68, 78, 88, 98]
[7, 17, 27, 37, 47, 57, 67, 77, 87, 97]
[6, 16, 26, 36, 46, 56, 66, 76, 86, 96]
[5, 15, 25, 35, 45, 55, 65, 75, 85, 95]
[4, 14, 24, 34, 44, 54, 64, 74, 84, 94]
[3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
[2, 12, 22, 32, 42, 52, 62, 72, 82, 92]
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]