vendredi 13 septembre 2019

Incompatible types while using weighted randomness in java

I tried to implement Weighted Randomness in Java

so I found following codes

  1. RandomCollection Class
  2. RandomTopic Class

    public class RandomCollection<E> {
      private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
      private final Random random;
      private double total = 0;
    
    public RandomCollection() {
    this(new Random());
    }
    
    public RandomCollection(Random random) {
    this.random = random;
    }
    
    public RandomCollection<E> 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 class RandomTopic {
    
    RandomCollection<String> rc = new RandomCollection<>().add(40, "dog").add(35, "cat").add(25, "horse");
    
    }
    
    

However, the IDE shows the following error at

"RandomCollection String rc"

Incompatible types.

Required: RandomCollection java.lang.String

Found: RandomCollection java.lang.Object

How can I solve the problem? please help




Aucun commentaire:

Enregistrer un commentaire