gpt4 book ai didi

java - 运算符 += 未定义参数类型 int、AtomicLong

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:19:20 32 4
gpt4 key购买 nike

我有一张 map 如下 -

ConcurrentHashMap<Long, AtomicLong> histogram = new ConcurrentHashMap<Long, AtomicLong>();

这张 map 包含很多键值对。将 AtomicLong 作为值是必要的,这就是我在该映射中这样放置的原因。

所以现在如果我尝试遍历我上面提到的 ConcurrentHashMap,它总是会在这一行给我错误-

buckets[i] += histogram.get(time);

as- 运算符 += 未定义参数类型 int,AtomicLong

我不确定如何解决这个问题?我无法返回并将数据结构更改为所有 Integer 而不是 LongAtomicLong

所以我需要找出如何更改下面的代码,以便它开始工作。我正在考虑转换为整数。但它也不起作用。

下面是我的代码

private static void logHistogramInfo() {

System.out.println("From Main Thread: " + histogram);

int[] definition = { 0, 20, 40, 60, 80, 100 };
int[] buckets = new int[definition.length];

for (Long time : histogram.keySet()) {
for (int i = definition.length - 1; i >= 0; i--) {
if (time >= definition[i]) {
//error on the below line
buckets[i] += histogram.get(time);
break;
}
}
}
for (int i = 0; i < definition.length; i++) {
String period = "";
if (i == definition.length - 1) {
period = "greater than " + definition[i] + "ms";
} else {
period = "between " + (definition[i] + 1) + " and " + definition[i + 1] + "ms";
}
System.out.println(buckets[i] + " came back " + period);
}

}

最佳答案

+= 运算符最初旨在与原始数据类型(intlong...)一起使用。由于这些不能放在 map 中,因此存在包装类。当您将 IntegerLong 与任何算术运算符一起使用时,它们会自动“拆箱”为其相应的原始类型。

但是,没有原始类型对应于任何AtomicXYZ。但是,您可以使用 Number 类提供的任何方法来获取其原始值,例如longValue()intValue()。请注意,原子 long 的值原则上可以大于最大的 int(或 Integer),因此您可能希望以某种方式处理潜在的溢出。

[edit] 或者您可以使用 get() 方法,正如 assylias 指出的那样(我不知道,因为我以前从未使用过原子类型),它与 longValue() for AtomicLong(和 intValue() for AtomicInteger 一样),从它的实现。

关于java - 运算符 += 未定义参数类型 int、AtomicLong,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14768112/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com