While working on my project, I made a function to select a random object from an ArrayList
. Each object has a variable min and max which defines the percentage the object has of being chosen.
The function works perfectly, but I use a dozen slight variations of it since I have a lot of ArrayList
s with different types of objects, which I need to use it on. Therefore, I want to make it generic so I'd only have one variant of the function, which I can use for all my lists. At the moment, I have this:
public static <G> int selRan(ArrayList<G> list){
int sel = 0;
Random rand = new Random();
int randNum = rand.nextInt(100) + 1;
for(int i = 0; i < list.size(); i++){
if(list.get(i).min <= randNum && randNum < list.get(i).max){
sel = i;
}
}
return sel;
}
This is where I ran into a snag, as list.get(i).min
and list.get(i).max
don't work. I have no clue on how to approach this.