package shineagent; import java.util.*; public class RandomCollection { private final NavigableMap map = new TreeMap(); private final Random random; private double total = 0; public RandomCollection() { this(new Random()); } public RandomCollection(Random random) { this.random = random; } public RandomCollection add(double weight, E result) { if (weight <= 0) return this; total += weight; map.put(total, result); return this; } public E next() { double value = random.nextDouble() * total; return map.higherEntry(value).getValue(); } public boolean isEmpty() { return (map.size() == 0); } }