I'm making a generic abstract class that will work with float and integer values and will use different algorithms to generate a new value. It relies heavily on picking a random value within range, so I wanted to make a generic RandomRange kind of function.
This is the example of my code and what I'm trying to achieve.
public abstract class SelectionAlgorythm < T > {
protected static Random random = new Random();
BiFunction < T, T, T > picker;
RangePair pair;
public abstract T value();
protected SelectionAlgorythm(RangePair < T > pair) {
this.pair = pair
if (pair.minRange instanceof Integer) {
picker = SelectionAlgorythm::pickRandomInt;
} else if (pair.minRange instanceof Float) {
picker = SelectionAlgorythm::pickRandomFloat;
}
}
private static Integer pickRandomInt(Integer val1, Integer val2) {
return random.nextInt((int) val2 - (int) val1) + (int) val1;
}
private static Float pickRandomFloat(Float val1, Float val2) {
return random.nextFloat() * (val2 - val1) + val1;
}
public T pickValue() {
return picker(pair.minRange, pair.maxRange);
}
}
However I run into problems here and I can't figure out how to fix them. If I leave the code as it is, then the picker initialization lines complain that "Incompatible types, T is not convertible to Integer"
But I also can't just make the functions themselves generic, because random.nextInt() and random.nextFloat() expect particular values, not generics.
How do I do that? I admit, I have not worked with generics much and kind of moved away from Java recently, so I may be missing something obvious.