How to randomly pick an element from an array

前端 未结 12 747
逝去的感伤
逝去的感伤 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:17

    public static int getRandom(int[] array) {
        int rnd = new Random().nextInt(array.length);
        return array[rnd];
    }
    

提交回复
热议问题