简体   繁体   English

确定哈希表的平均链长

[英]Determining HashTable average chain length

I'm trying to write some functions to display the average amount of buckets being used and the average chain length in my hashtable. 我正在尝试编写一些函数以显示哈希表中正在使用的平均存储桶数量和平均链长。 I dont know how to measure these things. 我不知道如何测量这些东西。

public Double bucketUsagePercentage(){

}
public Double avgChainLength(){

}

public void printStats(){
    System.out.println("LoadFactor: " + getTableLoad());
}

As already mentioned, you could actually wrap the Hashtable and then keep track of the inserted Object hashcodes + dynamically calculate the number of available buckets. 如前所述,您实际上可以包装哈希表,然后跟踪插入的对象哈希码+动态计算可用存储区的数量。 But, assuming you know the loadfactor (default 0.75) you can create static tools to "measure" any existing Hashtable (you can easily alter it to work for HashSets as well). 但是,假设您知道负载因子(默认值为0.75),则可以创建静态工具来“测量”任何现有的Hashtable(您可以轻松地对其进行更改以使其适用于HashSets)。

*Just to highlight that due to the initial capacity requirement, results may not be 100% accurate at the very beginning, because initial buckets are fixed until rehashing is required. *仅强调一下,由于初始容量要求,结果可能在一开始时并不是100%准确的,因为初始存储桶是固定的,直到需要重新哈希。

import java.util.Hashtable;

public class HashMetrics {


    public static double bucketUsagePercentage(Hashtable<?,?> a, double loadfactor) {
        int bucketSize = getBucketSize(a, loadfactor);
        int[] bucketFrequency = new int[bucketSize];
        for (Object k : a.keySet()) {
            bucketFrequency[k.hashCode() % bucketSize]++;
        }
        int counter = 0;
        for (int i : bucketFrequency) {
            if (i > 0) counter++;
        }
        return (double)counter / bucketSize;
    }

    //skip empty buckets (very similar to previous function, last line is only changed)
    public static double averageChainLength(Hashtable<?,?> a, double loadfactor) {
        int bucketSize = getBucketSize(a, loadfactor);
        int[] bucketFrequency = new int[bucketSize];
        for (Object k : a.keySet()) {
            bucketFrequency[k.hashCode() % bucketSize]++;
        }
        int counter = 0;
        for (int i : bucketFrequency) {
            if (i > 0) counter++;
        }

        return (double)a.size() / counter;
    }

    public static int log2(int number) {
        if(number == 0)
            return 0;
        return 31 - Integer.numberOfLeadingZeros(number);
    }

    public static int getBucketSize(Hashtable<?,?> a, double loadFactor) {
        int n = a.size();
        int bucketSize = 2 << log2(n);
        if (bucketSize * loadFactor <= n) {
            bucketSize <<= 1;
        }
        return bucketSize;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM