Home » Android » java – Passing an ArrayList of any type to a method

java – Passing an ArrayList of any type to a method

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

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

int randomIndex(int size){
    int n = randomGenerator.nextInt(size);
    return n;
}

Answer:

with this code you can pass any type of list

int randomIndex(List<?> list){
    int n = randomGenerator.nextInt(list.size());
    return n;
}

Answer:

just make it:

private int randomIndex(int size){
return randomGenerator(size);
}

And then call them with randomIndex(yourArray.size());

Answer:

More generic is to use List than ArrayList in method signature.

int your_method(List<?> a){
//your code
}

Answer:

you can use Generics as follows

declare your function as below

private <T> int randomIndex(ArrayList<T> a){
    int n = randomGenerator.nextInt(a.size());
    return n;
}

now you can pass ArrayList<String> or ArrayList<Integer> to this function without any issue like this

ArrayList<String> strList = new ArrayList<String>();
strList.add("on1");
System.out.println(randomIndex(strList));
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1);
System.out.println(randomIndex(intList));

Answer:

int randomIndex1(ArrayList<?> a)
{
   int n = randomGenerator.nextInt(a.size());
   return n;
}

int randomIndex2(int size)
{
   int n = randomGenerator.nextInt(size);
   return n;
}