I'm working on my first Android app, a math game for my kid, and am learning Java in the process. I have two ArrayLists, 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.
int) as an argument and return any random number between 0 and A and call this method passing your array list sizes.