【发布时间】:2018-11-12 08:50:10
【问题描述】:
好的,所以我有这段代码应该从加权列表中获取随机条目。但是,当我尝试调用 TreeMap.higherEntry 时,即使有更高的条目可用,它也会返回 null。 lowerEntry 确实有效,ceilingEntry 返回相同的 null。这是我的代码:
import java.util.*;
public class Randomizer<E> extends ArrayList<E> {
private Random rng;
private double defaultWeight;
public Randomizer(List<E> list) {
super(list);
rng = new Random();
defaultWeight = 1.0d;
}
/*Stripped some uninteresting constructor variations for clarity*/
public void setSeed(long seed) {
rng.setSeed(seed);
}
public E getRandom() {
TreeMap<Double,E> map = new TreeMap<>();
double total = 0;
for(E e : this) {
if(e instanceof Weighted) {
map.put(((Weighted) e).getWeight(),e);
total += ((Weighted) e).getWeight();
} else {
map.put(defaultWeight,e);
total += defaultWeight;
}
System.out.println(total);
}
double value = rng.nextDouble() * total;
System.out.println(value + ", " + map.higherKey(value));
return map.higherEntry(value).getValue();
}
}
这是一个小数据集的控制台输出:
5.0
9.0
11.0
14.0
15.0
15.5
19.5
22.5
24.0
26.5
27.5
28.0
9.987466924354226, null
Exception in thread "main" java.lang.NullPointerException
at me.datafox.utils.Randomizer.getRandom(Randomizer.java:52)
at me.datafox.grick.SwordTest.main(SwordTest.java:39)
我做错了什么吗?数据集的格式非常奇怪,所以我将其省略,但很明显,从权重列表计算总数不是我面临的问题。
【问题讨论】:
-
it returns null even though there is a higher entry available?你确定有更高的入口吗?您可以在调用map.higherKey(value)之前简单地打印map和value并亲自查看。 -
考虑到输出没有一个值似乎大于 5。所以地图不包含任何高于 9 的键。
-
似乎没有更高的条目。查看您正在打印的值:
System.out.println(total);- 这是根据total += ((Weighted) e).getWeight();添加的值的总和如果您查看打印端的总数,添加的最高值应该是 5.0 -
您将总计打印到控制台,而不是您添加的值。正如您在累积总值中看到的那样,没有添加高于 9.987466924354226 的值。最高值为 5.0。
-
@Eran 现在我觉得自己像个大白痴。睡了四个小时后,最简单的事情有点错过了你的雷达。
标签: java arrays dictionary nullpointerexception null