从包含N个元素的数组里,随机选取M个元素.

来源:互联网 发布:luci源码 编辑:程序博客网 时间:2024/04/26 10:28

public static Object[] randomSelect(Object[] objects, int select) {

    select = Math.abs(select);

    if (objects == null || objects.length == 0) {

        throw new IllegalArgumentException("Input Array cann't be null or empty");

    }

    if (select > objects.length) {

       throw new IllegalArgumentException("Select number cann't be larger than the length of the array");  

    }

    Object[] result = new Object[select];

    Random random = new Random();

    int rIndex = 0;

    Object t = null;

    for (int i = 0; i < select; i++)  {

        rIndex = random.nextInt((objects.length - 1) - i);

        result[i] = objects[rIndex];

        t = objects[i];

        objects[i] = objects[rIndex];

        objects[rIndex] = t;

    }

    return result;

}

原创粉丝点击