我看了一篇来自
JavaDays的代码,作者说这种方法有概率非常有效,可以将类似String的字符串存储到String实习方法
public class CHMDeduplicator {
private final int prob;
private final Map map;
public CHMDeduplicator(double prob) {
this.prob = (int) (Integer.MIN_VALUE + prob * (1L << 32));
this.map = new ConcurrentHashMap<>();
}
public T dedup(T t) {
if (ThreadLocalRandom.current().nextInt() > prob) {
return t;
}
T exist = map.putIfAbsent(t,t);
return (exist == null) ? t : exist;
}
}
请解释一下,这一行中概率的影响是什么:
if (ThreadLocalRandom.current().nextInt() > prob) return t;
本文介绍了一种利用概率和ConcurrentHashMap实现的字符串去重方法。通过调整概率参数,可以在性能和内存消耗之间找到平衡点。代码示例展示了如何使用ThreadLocalRandom和ConcurrentHashMap来高效地去除重复字符串。
171万+

被折叠的 条评论
为什么被折叠?



