【问题标题】:Finding how many number of keys are there in a bucket查找存储桶中有多少个键
【发布时间】:2025-12-06 03:15:02
【问题描述】:

当多个键具有相同的哈希码时,就会发生冲突。在这种情况下,键值条目以映射到存储桶的链表格式存储。现在我想知道给定存储桶存在多少这样的 Map.Entry 对。有没有内置的java方法可以帮助我识别?

bucket1 ----> (10, 1) ---> (100, 2) --- 在这种情况下答案是 2。

bucket2 ----> (2, 1) ---- 答案是 1。

bucket3 ----> (3, 5) ---> (6, 10) ---> (9, 15) ---> (12, 18) ---- 在这种情况下回答 4 .

对此的任何帮助都会很棒。

【问题讨论】:

    标签: java algorithm data-structures hashmap hashtable


    【解决方案1】:

    除非您使用集合作为地图的值,否则您将不能为特定存储桶拥有多个值。检查put() 将在文档中为HashMap 做什么

    使用列表作为地图的值,您可以尝试以下操作:

    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Playground {
    
        public static void main(String[] args) {
            Map<Integer, List<Pair>> map = new LinkedHashMap<Integer, List<Pair>>();
    
            map.put(1, Arrays.asList(new Pair(10, 1) , new Pair(100, 2)));
            map.put(2, Arrays.asList(new Pair(2, 1)));
            map.put(3, Arrays.asList(new Pair(3, 5), new Pair(6, 10), new Pair(9, 15), new Pair(12, 18)));
    
            for (Map.Entry<Integer, List<Pair>> entry : map.entrySet()) {
                System.out.println(String.format("Bucket %d has %d item(s)", entry.getKey(), entry.getValue().size()));
            }
        }
    }
    
    class Pair {
        Integer x;
        Integer y;
    
        Pair(Integer x, Integer y) {
            this.x = x;
            this.y = y;
        }
    }
    

    您的输出将如下所示:

    Bucket 1 has 2 item(s)
    Bucket 2 has 1 item(s)
    Bucket 3 has 4 item(s)
    

    希望有帮助

    【讨论】:

    • 我不认为这回答了我的问题(或者我问的问题可能不太清楚)。假设,我有一个桶大小为 5 的 hashmap/hashtable。为了计算哈希码,我使用 mod 5 运算符作为哈希函数。前 5 个键,即 1,2,3,4,5 将占用桶 1 到 5。当我插入键 6 和一些值时,它会被添加到桶 1。因此桶 1 的大小现在是 2。这个是我要找的。​​span>
    • 我明白你的意思。我不认为桶的信息会暴露。快速查看source code,你想要的信息就在里面,只是不公开而已。
    • 谢谢,只是在同一页面上,您指的是 addEntry/createEntry 方法吗?
    • table 属性首先引起了我的注意,但是您提到的方法也很相关。他们最终修改了table
    最近更新 更多