I'm working on my first Android app, a math game for my kid, and am learning Java in the process. I have two ArrayList
s, one of integers 0..9
and one strings of possible operations, at present, just +
and -
.
I would like to write a method that returns a random index into an ArrayList
, so I can select a random element. What I'm running into is that I need two methods, one for each type of ArrayList
, even though the code is identical. Is there a way to do this in a single method?
What I use now:
Random randomGenerator = new Random();
. . .
n = randomIndexInt(possibleOperands);
int op1 = possibleOperands.get(n);
n = randomIndexInt(possibleOperands);
int op2 = possibleOperands.get(n);
n = randomIndexStr(possibleOperations);
String operation = possibleOperations.get(n);
. . .
int randomIndexInt(ArrayList<Integer> a){
int n = randomGenerator.nextInt(a.size());
return n;
}
int randomIndexStr(ArrayList<String> a){
int n = randomGenerator.nextInt(a.size());
return n;
}
What I'd like to do is collapse randomIndexInt
and randomIndexStr
into a single method.
declare your method as int randomIndexInt(ArrayList<?> a)
You need only the size of the array right? so do it:
int randomIndex(int size){
int n = randomGenerator.nextInt(size);
return n;
}
with this code you can pass any type of list
int randomIndex(List<?> list){
int n = randomGenerator.nextInt(list.size());
return n;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With