Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an ArrayList of any type to a method

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.

like image 816
codingatty Avatar asked Jul 31 '12 07:07

codingatty


3 Answers

declare your method as int randomIndexInt(ArrayList<?> a)

like image 102
didxga Avatar answered Sep 28 '22 06:09

didxga


You need only the size of the array right? so do it:

int randomIndex(int size){
    int n = randomGenerator.nextInt(size);
    return n;
}
like image 23
Nermeen Avatar answered Sep 28 '22 07:09

Nermeen


with this code you can pass any type of list

int randomIndex(List<?> list){
    int n = randomGenerator.nextInt(list.size());
    return n;
}
like image 39
neworld Avatar answered Sep 28 '22 08:09

neworld