Passing an ArrayList of any type to a method

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.

+6
source share
7 answers

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

+13
source

Do you need only the size of the array? do it:

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

with this code you can pass any type of list

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

just do it:

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

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

+2
source

More general is the use of List than ArrayList in the method signature.

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

you can use Generics as follows

declare your function below

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

you can now pass an ArrayList<String> or ArrayList<Integer> this function without any problems 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)); 
+1
source
 int randomIndex1(ArrayList<?> a) { int n = randomGenerator.nextInt(a.size()); return n; } int randomIndex2(int size) { int n = randomGenerator.nextInt(size); return n; } 
0
source

Source: https://habr.com/ru/post/921740/