How to randomly pick an element from an array

前端 未结 12 746
逝去的感伤
逝去的感伤 2020-11-22 16:48

I am looking for solution to pick number randomly from an integer array.

For example I have an array new int[]{1,2,3}, how can I pick a number randomly?

12条回答
  •  遇见更好的自我
    2020-11-22 17:14

    You can use the Random generator to generate a random index and return the element at that index:

    //initialization
    Random generator = new Random();
    int randomIndex = generator.nextInt(myArray.length);
    return myArray[randomIndex];
    

提交回复
热议问题