I am working on my first Android application, a math game for my child, and learning Java in the process. I have two ArrayList
s, one of the integers 0..9
and one line of possible operations, currently, only +
and -
.
I would like to write a method that returns a random index in an ArrayList
, so I can select a random element. I work in that I need two methods: one for each type of ArrayList
, although the code is identical. Is there a way to do this in one method?
What i am using 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 would like to do is collapse randomIndexInt
and randomIndexStr
into one method.
source share